-2

我试图在java中绘制图像。在我创建一个单独的类来存储图像之前,它正在工作。但现在我得到空指针异常。

主类:

Image image;
Images images; // class object
public void paint(Graphics G){
    image = images.GETImage();
    G.drawImage(image, x, y, 20,20,null);
}

protected void paintComponent(Graphics G){
    paint(G);       
}

用于存储图像的 Image 类:

public Image GETImage(){
    int direction = pacman.getDirection();
    int newDirection = pacman.getDirection();
    int x = pacman.getX();
    int y = pacman.getY();

    if(direction == Constant.UP){
        ImageIcon i = new ImageIcon("src\\images\\pacman up.png");
        image = i.getImage();

        }
    return image;
}
4

1 回答 1

4

你的问题在这里:

Image image;
Images images; // class object (this is never initiated in code snippet given)
public void paint(Graphics G){
    image = images.GETImage(); //images is null, thus calling any method on the object will throw NPE
    G.drawImage(image, x, y, 20,20,null);
}

你永远不会启动images,因此它会抛出一个 NPE。

另请注意@HovercraftFullOfEels 的评论,这很重要,尤其是方法的命名

于 2012-12-03T19:19:53.403 回答