开发者

Unable to change the jFrame icon / load a resource for a .jar with Eclipse

开发者 https://www.devze.com 2022-12-15 23:46 出处:网络
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:

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开发者_JAVA百科.

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


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


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消