Load images in jar file

岁酱吖の 提交于 2019-12-10 10:17:16

问题


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.


回答1:


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); 


来源:https://stackoverflow.com/questions/18547780/load-images-in-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!