我试图在java中绘制图像。在我创建一个单独的类来存储图像之前,它正在工作。但现在我得到Null指针异常。
主要课程:
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);
}
用于存储图像的图像类:
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;
}
答案 0 :(得分: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的评论,这对于您的方法命名非常重要