tags:

views:

225

answers:

2

I'm trying to load an ImageIcon as described here, but I'm getting an error. Tried the method here too, but ran into the same error. It says:

"Uncaught error fetching image:
java.lang.NullPointerException..."

I couldn't find a solution to this. I can load the image icon using this:

setIconImage(new ImageIcon("etc/image.png").getImage());

But then it doesn't work with a .jar.

EDIT: using

Image im = ImageIO.read(new File("etc/image.png"));  

And then creating the ImageIcon gives me no errors, but doesn't work with the .jar, even if I use the Export option as described here.

EDIT 2: Okay, putting my /etc folder inside the /bin folder created for the project solved this. I have ABSOLUTELY NO IDEA why, so I'd be thankful if someone could explain that one to me. Wait, nevermind that. It doesn't work for the .jar.

EDIT 3: Solution to the problem here.

Basically, you create a folder within /src and then import the files into it. Man, I can't believe I lost so much time over this. RAGE

A: 

I use this snippet, replace Config with your classname.

public static ImageIcon loadImageIcon(String filename) {

    URL url = Config.class.getClassLoader().getResource( IMAGE_DIR + filename);
    if (url == null) {
        System.err.println("No image for " + filename);
        return null;
    }
    ImageIcon icon = new ImageIcon(url);
    return icon;
}
stacker
that code is returning null to me. i don't get it, the image is there.
zxcvbnm
sorry to hear that, do you get the "no image" msg first, so you have no class-loader issue. are you trying to load big images? so may wan't to combine both suggestions. I used this to load 16x16 icons, and i never had white spots in my app
stacker
A: 

When creating the ImageIcon, the image is loaded in a seperate Thread. So it is possible the image is not yet loaded after creating the ImageIcon.

What you could try is the following (simple solution, better is to use some kind of listener I think):

ImageIcon imageIcon = new ImageIcon("etc/image.png");

int loadingDone = MediaTracker.ABORTED | MediaTracker.ERRORED | MediaTracker.COMPLETE;

while((imageIcon.getLoadStatus() & loadingDone) == 0){
   //just wait a bit...
}
if(imageIcon.getLoadStatus() == MediaTracker.COMPLETE)
    setIconImage(imageIcon.getImage());
else {
    //something went wrong loading the image...
} 

MediaTracker is java.awt.MediaTracker

Fortega