getResource() -> Source not found

我们两清 提交于 2019-12-23 01:04:48

问题


I'm following the tutorial here. The file is in the same root folder of the project. I've tried doing it when it's in the src folder and in the same package folder. None of those 3 locations worked.

The specific line of code is:

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

Any idea what I'm doing wrong?


回答1:


// 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:


The getResources(...) method looks for the file relative to where the default class loader looks, and so for your code above, bardejov.jpg would need to be with the class files to be found. Myself, I usually create a subdirectory off of the class file directory, say called "images" and place my images there, and then look for them using getClass().getResource("images/bardejov.jpg")

For more on this, please check out the Class API.




回答3:


If your image is in the same folder then it would work, but if your image is in root folder then use /bardejov.jpg.



来源:https://stackoverflow.com/questions/8483731/getresource-source-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!