Search code examples
javaeclipseswingjarembedded-resource

Java Swing: Runnable JAR file does not work when including images


The code below works fine in Eclipse (both image-handling possibilities). But when exporting as a Runnable JAR File, and double-clicking the .JAR, nothing happens. If I comment out the image parts of the code, the .JAR runs fine as an export and the frame builds. So it seems the getting of the image is causing the .JAR to fail.

I've got the strawberry.jpg file sitting in 'C:\Users\sean\workspace\myApps\bin\testing' Could you advise if the issue is with my code?

(Code first modified here: Java Swing: unable to load image using getResource)

package testing;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;



public class IconTest {


public static void main(String[] arguments) throws IOException {

    JFrame frame1 = new JFrame();
    frame1.setTitle("Frame1");
    frame1.setSize(500, 500);
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    FlowLayout flo = new FlowLayout();
    frame1.setLayout(flo);

    //POSSIBILITY 1 TO HANDLE IMAGE
      InputStream resourceAsStream = IconTest.class.getResourceAsStream("strawberry.jpg");
    Image image = ImageIO.read(resourceAsStream);
    JLabel label1 = new JLabel(new ImageIcon(image));

    //POSSIBILITY 2 TO HANDLE IMAGE
/*    java.net.URL url= IconTest.class.getResource("strawberry.jpg");
    BufferedImage watermarkImage = ImageIO.read(url);
    JLabel label1 = new JLabel(new ImageIcon(watermarkImage));*/


    frame1.add(label1);
    frame1.setVisible(true);
}

}


Solution

  • The guidance offered here in troubleshooting the problem helped greatly - thank you to everyone. I tested contents of an exported JAR; I used diagnostic code suggested by Kishan to determine if my code could "see" the image. I believe it might have something to do with the way Eclipse works/refreshes if I move images around in the file system instead of the Eclipse import function. Finally, in order to get it to work, I made the following changes: I created a new project and two sub-packages - one for 'resources' and one for my code class. Then I right-clicked > import on the resources package in Eclipse to get the image.

    The only thing to change in my code is ....getResourceAsStream("/resources/strawberry.jpg");