java - 无法在我的 java 示例中加载照片

标签 java eclipse swing nullpointerexception imageicon

我正在尝试做这个例子 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/

相关文章:

java - 数组构造上的断点

java - 将数组列表中的文本放在单独的行中

java - 如何在 RxJava 中进行递归 Observable 调用?

Java Grect 和私有(private)静态错误

java - Facebook 与 Libgdx 集成

java - 简单 Java 程序中的意外错误

java - 第一次运行JAR时在桌面创建快捷方式

java - JTable中添加Image时显示的字符串路径

java - 如果没有 @Repository 注释,代码可以正常工作,而使用注释也可以正常工作。有什么不同?

java - java中的条件正则表达式