文件引用无效,我哪里错了?

时间:2013-12-07 21:47:24

标签: java image nullpointerexception embedded-resource imageicon

每当我尝试使用paintComponent和ImageIcon绘制图像时,我从未知来源获取NullPointerException,然后指向我的图像获取器并开始线程。

Image getter

ImageIcon image = new ImageIcon(this.getClass().getResource("C:/Users/Rhys/Desktop/workspace/Mindcracker RPG/Res/Background.jpg"));

感谢您的回答

1 个答案:

答案 0 :(得分:1)

使用JavaDoc:

this.getClass().getResource()仅用于获取ClassPath/代表default package的资源。

您提供的是一条完全合格的路径。

您需要做的是使用此constructor

public ImageIcon(String filename) 
  

从指定的文件创建ImageIcon。

     

指定的String可以是文件名或文件路径。什么时候   指定路径,使用Internet标准正斜杠(" /")作为   分隔器。 (字符串转换为URL,因此正斜杠   适用于所有系统。)

例如,请指定:

new ImageIcon("C:/Users/Rhys/Desktop/workspace/Mindcracker RPG/Res/Background.jpg");

请注意路径中有一个空格,此路径最终会转换为file:://网址,因此您可能需要考虑这一点