如何在applet上绘制图像

时间:2014-05-17 17:36:21

标签: java awt paint bufferedimage

public class ImageExample2 extends Applet
{

    BufferedImage bi;


    public void init ()
    {

        resize (500, 500);

        try
        {

            BufferedImage bi = ImageIO.read (new File ("G:\\Java\\WhatDotColour\\Pacman.PNG"));
        }
        catch (java.io.IOException e)
        {
            e.printStackTrace ();
        }
    }


    public void paint (Graphics g)
    {

        g.drawImage (bi, 20, 140, this); //.drawImage(in, 0, 0, null);

    }
}

每次我尝试运行它时,它都会给我一个空指针异常。我该如何解决?

2 个答案:

答案 0 :(得分:1)

不要AppletFile混合。它们就像石油和油水。 Applet在浏览器中运行。始终使用相对路径。

使用Applet#getCodeBase()获取基本网址。这是包含此applet的目录的URL。

示例代码:(查看getCodeBase()方法的输出并修改图像路径)

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;

public class ImageExample2 extends Applet {

    private Image bi;

    public void init() {

        resize(500, 500);

        System.out.println(getCodeBase()); // file:/D:/Workspace/JavaProject/bin/

        // This the actual code that should be used to read the image in Applet
        bi = getImage(getCodeBase(), "images/222.png");
    }

    public void paint(Graphics g) {
        g.drawImage(bi, 20, 140, this);

    }
}

如果您使用的是Windows& Eclipse IDE然后查看下面显示的截图,以获取上面的示例代码图像路径。

enter image description here

答案 1 :(得分:0)

变化:

BufferedImage bi=ImageIO.read (new File ("G:\\Java\\WhatDotColour\\Pacman.PNG"));

bi = ImageIO.read (new File ("G:\\Java\\WhatDotColour\\Pacman.PNG"));

并更改

g.drawImage (bi, 20, 140, this); //.drawImage(in, 0, 0, null);

if (bi!=null) g.drawImage (bi, 20, 140, this); //.drawImage(in, 0, 0, null);
相关问题