简体   繁体   English

我的Java示例无法加载照片

[英]Can't load a photo in my java example

I'm trying to do this example http://zetcode.com/tutorials/javagamestutorial/movingsprites/ but i get these errors 我正在尝试执行此示例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)

I have tried putting my image in various places inside my project file and even writing the absolute path. 我尝试将图像放在项目文件中的各个位置,甚至编写绝对路径。

What do i do wrong? 我做错了什么? I use eclipse. 我用日食。

edit: Excuse me here's the code 编辑:对不起,这是代码

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

This one above is my current try while the example suggests: 以上是我目前的尝试,而示例则建议:

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

The exception is thrown from ImageIcon constructor. ImageIcon构造函数引发异常。 Looks from the sample like ImageIcon is initialized with URL , this constructor : 从示例中看起来像ImageIcon是使用URL初始化的,此构造函数是

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

The reason is probably due to the missing file "craft.png" in your workspace. 原因可能是由于工作空间中缺少文件“ craft.png”。 Make sure that loader can find the specified file and this.getClass().getResource(craft) is not null. 确保加载程序可以找到指定的文件,并且this.getClass().getResource(craft)不为null。

See Loading Images Using getResource tutorial for details and some examples how to add and load images and other resources. 有关详细信息以及如何添加和加载图像及其他资源的示例,请参见使用getResource加载图像教程。

this.getClass().getResource is mainly used if you run code from jar file and you need to load resources that are also inside jar. this.getClass().getResource主要用于从jar文件运行代码并且需要加载也在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. 如果您的图片在您的项目中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM