我在最新游戏中设置图像时遇到问题。当我调用方法getImage(String)
时,我得到这样的图像:
Image head = getImage("Torso_model_01.png");
我收到以下错误消息:
Err: java.lang.NullPointerException
At PB2Main.Body(Body.java : 27)
...
等等...
在本教程中,它解释了如何使用 ImageIcon 获取图像,如下所示:
String imgFile = "Images/" + img;
URL imgURL = getClass().getClassLoader().getResource(imgFile);
ImageIcon imageIcon;
Image image;
if(imgURL != null){
imageIcon = new imageIcon(imgURL);
image = imageIcon.getImage();
}
final Image anImage = image;
我为此做了一个方法:
public URL getURL(String img){
String imgFile = "Images/" + img;
URL imgURL = getClass().getClassLoader().getResource(imgFile);
return imgURL;
}
然后我做了一个名为 getImage(String) 的方法
public Image getImage(String img) {
ImageIcon imageIcon;
Image image;
URL imgURL = getClass().getClassLoader().getResource(getURL(img));
if(imgURL != null){
imageIcon = new ImageIcon(imgURL);
image = imageIcon.getImage();
return image;
}
System.err.println("Unable to Locate Image: " + imgURL);
}
现在,我有一个名为Body
. 在那个类中,我有一个构造函数:
public Body(float x, float y, String head, String torso){//atm this is just so i can get the image to actually draw on the screen
Image Head = debugger.getImage(head);// debugger doubles as a library and debugger
//i also can't have this class extend debugger otherwise it will create a window :/
// is that a glitch or something in Java? :L perhaps i just don't understand
// inheritance very well and what happens exactly when you inherit a class :(
Image Torso = debugger.getImage(torso);
g2.drawImage(Head, canvas.geWidth()/ 2,canvas.getHeight()/2, null)// canvas: the window to
//draw to
// can someone also quickly explain in their answer what an image observer is please?
g2.drawImage(Torso, Head.getX() - 5, Head.getY() - 5, null);
}
编译器给了我以下错误信息:
java.lang.NullPointerException
At PlazmaBurst2.Body(Body.java: 37)
//the code it brings me to is line 1 in the constructor:
/* null: */ Image Head = debugger.getImage(img);
我不明白这个 NullPointerException 是从哪里来的。我完全按照他们在同一站点的“自定义图形编程”部分中的操作方式进行了操作。
如果我只是复制和粘贴代码,代码就可以正常工作,但如果我使用 method 就不行getImage(String)
。