ImageIcons on JButton are not showing up in Runnable JAR file

試著忘記壹切 提交于 2019-12-18 06:48:24

问题


I have 6 JButtons on my GUI all have images on it, when I compile and run the code, all images on JButtons show up perfectly but in runnable JAR file, images on JButtons are not showing up.. how do I fix this problem?

I used this method in my code to show icons on JButtons

ImageIcon SettingsIc = new ImageIcon("bin/images/settings.png");
jb1 = new JButton(SettingsIc);
jb1.setFocusPainted( false );
//jb1.setBorderPainted(false); 
jb1.setContentAreaFilled(false);

This is how my GUI looks when I compile my code in Eclipse

This is how my GUI looks after executing Runnable JAR file


回答1:


This (as pointed out by a number of people)

ImageIcon SettingsIc = new ImageIcon("bin/images/settings.png");

Suggests that you are trying to load the images from the bin/images off the file systems. This is a relative path from the execution point of your application.

ImageIcon won't complain if the file does not exist.

If possible, you are better off embedding the resources within your Jar file (it will make it easier to deploy) and use something like getClass().getResource("/bin/images/settings.png") to load the images.

If possible, you should try using ImageIO.read(URL) to load your images, it will throw an exception if the resource pointed to by the File/URL does not exist (or is invalid).




回答2:


Just keep the jar and images in the same folder and keep

ImageIcon icon = new ImageIcon("image.jpg");

in the code



来源:https://stackoverflow.com/questions/14596487/imageicons-on-jbutton-are-not-showing-up-in-runnable-jar-file

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