Can not load the images in Java Swing when running from a .jar-file

自古美人都是妖i 提交于 2019-12-24 01:24:48

问题


I can run my Java Swing application from Eclipse without problems. But when I run it from a .jar-file, the images fails to load.

I load my images with:

setIconImage(Toolkit.getDefaultToolkit().
getImage(getClass().getResource("../images/logo.png")));

How can I load the images so they work even when I'm running from a .jar-file?

The images is in the same Jar-file, in the packet com.example.images and the class where they are used is in com.example.gui.dialogs


回答1:


Use the absolut path inside your jar. If you don't know it, try opening the JAR with a zip programm, e.g. 7zip. Then use the absolute path:

getClass().getResource("/com/examples/images/logo.png")

This obiously only works when your image is in your jar. If its not, but in your classpath, this should be fine too.




回答2:


The images should be packed as well in a jar file. Actually, I'm not 100% sure there is no other solution, but at least I made it work this way, when experimenting the same issue.

The jar was then added to the classpath, and I'm accessing image resources this way:

getResource("images/logo.png");



来源:https://stackoverflow.com/questions/2927334/can-not-load-the-images-in-java-swing-when-running-from-a-jar-file

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