我正在尝试做这个例子 http://zetcode.com/tutorials/javagamestutorial/movingsprites/ 但我收到这些错误
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at rtype.Craft.<init>(Craft.java:19)
at rtype.board.<init>(board.java:28)
at rtype.Rtype.<init>(Rtype.java:9)
at rtype.Rtype.main(Rtype.java:20)
我尝试将图像放在项目文件中的各个位置 甚至写出绝对路径。
我做错了什么? 我用的是eclipse。
编辑:对不起,这是代码
private String craft = "craft.png";
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public Craft() {
ImageIcon ii = new ImageIcon(this.getClass().getResource("C:\\Users\\Name\\workspace\\Craft\\src\\resource\\craft.png"));
image = ii.getImage();
x = 40;
y = 60;
}
上面的这个是我当前的尝试,而示例表明:
ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
最佳答案
this.getClass().getResource
主要用于从 jar 文件运行代码并且需要加载也在 jar 内的资源。
在您的情况下,您可能应该将其加载为
ImageIcon ii = new ImageIcon("C:/Users/Name/workspace/Craft/src/resource/craft.png");
image = ii.getImage();
或者甚至
ImageIcon ii = new ImageIcon("craft.png");
image = ii.getImage();
如果您的图像位于您的项目内部。
关于java - 无法在我的 java 示例中加载照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15710682/