ImageIcon Loading in Java

ぃ、小莉子 提交于 2019-12-08 06:24:17

When loading resources over a class, the path is relative to the package path, unless you have a leading slash /.

As for your icon1.gif, using

URL url = getClass().getResource("resources/icon1.gif");

should return the correct URL.

I recommend keeping the Java sources and resources separate. If resources is a source folder (whose output folder is the root of bin/the JAR), use:

URL url = getClass().getResource("/icon2.gif");

(note the leading slash).


EDIT (question updated):
Corrected the second URL (resources is a source folder, and icon2.gif lies in its root).
I just verified it in Eclipse, and I get the correct (non-null) URLs for both variants. Using the URLs in ImageIcons also gives the correct results, the images are shown.

  • Make sure that resources is a source folder. Not all project files land in the output folder (usually bin) and later the JAR.
  • Check your output folder to verify it contains the compiled classes as well as the resources.

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