0

我正在尝试执行此示例 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)

我曾尝试将我的图像放在项目文件中的各个位置,甚至编写绝对路径。

我做错了什么?我使用日食。

编辑:对不起,这是代码

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));
4

2 回答 2

2

构造函数抛出异常ImageIcon。从示例中看,这个构造函数ImageIcon初始化为:URL

String craft = "craft.png";
...
ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));

原因可能是由于您的工作区中缺少文件“craft.png”。确保加载器可以找到指定的文件并且this.getClass().getResource(craft)不为空。

See Loading Images Using getResource tutorial for details and some examples how to add and load images and other resources.

于 2013-03-29T20:16:04.507 回答
2

this.getClass().getResource is mainly used if you run code from jar file and you need to load resources that are also inside jar.

In your case you should probably just load it as

ImageIcon ii = new ImageIcon("C:/Users/Name/workspace/Craft/src/resource/craft.png");
image = ii.getImage();

or maybe even

ImageIcon ii = new ImageIcon("craft.png");
image = ii.getImage();

if your image is inside of your project.

于 2013-03-29T20:24:58.323 回答