2012-12-03 122 views
-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);  
} 

图像类存储图像:

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; 
} 
+1

使用调试器的命名。 QED。 – mre

+1

哪一行是空的?并改变不与已存在的paint方法冲突的'paint(Graphics g)'方法的名称。使用'myPaint(...)'或者这个想法。 –

+0

另外,如果这是我的应用程序,并且图像足够小,我会在课程创建时读取所有图像,并且在程序运行时不会一直读取同一图像。这是非常低效的。另外,你确定ImageIcon不是空的,因为它没有找到图像。为什么要创建一个ImageIcon,如果你打算将它用作图像? –

回答

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的意见,这是特别重要的方法

+1

Stackoverflow有一个自动化的过程,将删除连续的反对票。 gbtimmon的评论之一被标记为不适当的,但可能由主持人删除(适当)整个讨论。 –

+0

@HovercraftFullOfEels告诉我关于它我甚至没有期望做任何事情+1 stackoverflow :) –