getResource() - >来源未找到

时间:2011-12-13 02:46:21

标签: java embedded-resource imageicon

我正在关注教程here。该文件位于项目的同一根文件夹中。当我在src文件夹和同一个包文件夹中时,我已经尝试过这样做了。这3个地点都没有工作。

具体的代码行是:

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

知道我做错了吗?

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分:2)

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

查找它们

有关详情,请查看Class API

答案 2 :(得分:1)

如果您的图片位于同一文件夹中,则可以使用,但如果您的图片位于根文件夹中,请使用/bardejov.jpg。