Java images not appearing in JAR file [duplicate]

2019-06-11 22:31发布

问题:

This question already has an answer here:

  • Java Swing: Displaying images from within a Jar 5 answers

Heres how i call the image

Icon logoOne = new ImageIcon("logo.png");
// LOGO
JLabel imageLogo = new JLabel(logoOne); 
imageLogo.setPreferredSize(new Dimension(200, 50));

Its just added to a panel in a JFrame and works fine when running in eclipse but doesnt show up when exported to JAR.

can anyone help ?

回答1:

When exporting your JAR file, you've to make sure you're also including the image files in your JAR file. For example: If you have a folder called 'res' containing the images, you have to check the checkbox before this folder in order to make sure this folder, and the images are being included.

You might want to add some trouble shooting code. For example: Add some code that prints in the console if this image file exists. Export your JAR file, run your JAR via the console/terminal and check the result. If this shows you the image doesn't exists, you know it's a problem with your exported JAR file.

You might want to try reaching the image as a resource steam, give the following code sample a try:

java.net.URL logoOneUrl = getClass().getResource("logo.png");
Icon logoOne = new ImageIcon(logoOneUrl );


回答2:

When you call

Icon logoOne = new ImageIcon("logo.png");

You are reading the image from a file (see javadoc). When you export to the jar, this file is no longer available, so you need to use ClassLoader#getResourceFromClasspath() or use one of the other constructors.



回答3:

That depends on how you added the Image to the jar file.

In the normal case, the image lies in one of your source folders, and eclipse takes care of exporting it into the Jar file. If that is the case, you can load the via the ClassLoader. there are several methods for that. I mostly use this.getClass().getResourceAsStream("logo.png"). If you only use the standard Classloader (which would be the normal case) this will work.



回答4:

Don't get your image as a file as you're currently doing so. Instead get it as a resource. If you search this site, you'll find similar questions about occurring 2-4 times per week.

i.e.,

String imageResource = //.... string to image resource path
Image myImage = ImageIO.read(getClass().getResourceAsStream(imageResource));
Icon logo = new ImageIcon(myImage);

Note that the imageResource String is the String that represents the resource path to your image. This will depend on where your image is held in the jar file and where it is relative to the class files, information that we don't know at the moment.