2011-12-13 35 views
1

我正在关注教程here。该文件位于项目的同一个根文件夹中。我已经试过在src文件夹和相同的包文件夹中。这三个地点都没有工作。getResource() - >来源未找到

特定的代码行是:

ImageIcon ii = new ImageIcon(this.getClass().getResource("bardejov.jpg")); 

任何想法,我做错了吗?

+0

[Java中的Eclipse可能的重复:我在哪里把文件放在我想使用getResource加载的文件系统上? (例如ImageIcon的图像)](http://stackoverflow.com/questions/270197/java-in-eclipse-where-do-i-put-files-on-the-filesystem-that-i-want-to -load-usin) – Barett

回答

3
// absolute from the classpath 
MyClass.class.getResource("/myfolder/abc.txt"); 
// relative to the class location 
MyClass.class.getResource("abc.txt"); 
// another relative to the class location 
MyClass.class.getResource("myfolder/abc.txt"); 
2

getResources(...)方法查找相对于默认类加载器看起来的文件,因此对于上面的代码,bardejov.jpg需要与要找到的类文件一起使用。我自己,我通常创建一个类文件目录的子目录,称为“图像”,并将图像放在那里,然后使用getClass().getResource("images/bardejov.jpg")

欲了解更多信息,请查看Class API

+0

哦...忘了试一下。奇怪考虑我有一个类似的问题与DLL文件和VC++中的调试。这种方法是最好的方法吗? – Portaljacker

+0

@Portaljacker:如果将它们保存在jar文件中,则需要以这种方式获取资源。 –

+0

有一天我会学习制作罐子。 :P – Portaljacker

1

如果你的图像在同一个文件夹中,那么它将工作,但如果你的图像在根文件夹中,然后使用/ bardejov.jpg。