3

I'm trying to load an image from an executable JAR file.

I've followed the information from here, then the information from here.

This is the function to retrieve the images:

public static ImageIcon loadImage(String fileName, Object o) {
     BufferedImage buff = null;
     try {
        buff = ImageIO.read(o.getClass().getResource(fileName));
        // Also tried getResourceAsStream
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    if (buff == null) {
        System.out.println("Image Null");
        return null;
    }
    return new ImageIcon(buff);
}

And this is how it's being called:

logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());

With this being a simple Object. I'm also not getting a NullPointerException unless it is being masked by the UI.

I checked the JAR file and the image is at:

/pictures/Logo1.png

This current code works both in eclipse and when it's been exported to a JAR and run in a terminal, but doesn't work when the JAR is double clicked, in which case the icon is the default JFrame icon.

Thanks for you're help. It's probably only me missing something obvious.

Community
  • 1
  • 1
Adude11
  • 605
  • 5
  • 16
  • It is working fine on my side, even when I double click the `JAR` file or if I run it through `command prompt`. I created [this project](https://www.dropbox.com/s/32txnn42zxwebzi/SwingTest.zip) in eclipse juno, you can test that too :-) – nIcE cOw Aug 31 '13 at 12:12
  • What heppens if you do - `return new ImageIcon(getClass().getResource("/pictures/Logo1.png"));` directly? – SSaikia_JtheRocker Aug 31 '13 at 12:22

1 Answers1

2

I had a similar problem once, which turned out to be down to issues relative addressing and my path being in the wrong place somehow. I dug this out of some old code I wrote that made it use an absolute path. That seemed to fix my problem; maybe it will work for you.

String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this); 
Ultimate Gobblement
  • 1,851
  • 16
  • 23