3

我正在尝试从可执行 JAR 文件加载图像。

我已经关注了这里的信息,然后是这里的信息。

这是检索图像的功能:

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

这就是它的名称:

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

这是一个简单的对象。我也没有收到NullPointerException,除非它被 UI 屏蔽。

我检查了 JAR 文件,图像位于:

/图片/Logo1.png

此当前代码在 eclipse 中以及将其导出到 JAR 并在终端中运行时都有效,但在双击 JAR 时不起作用,在这种情况下,图标是默认的 JFrame 图标。

谢谢你的帮助。可能只有我错过了一些明显的东西。

4

1 回答 1

2

我曾经遇到过类似的问题,结果证明是相对寻址问题以及我的路径以某种方式位于错误的位置。我从我写的一些旧代码中挖出了这个,使它使用绝对路径。这似乎解决了我的问题;也许它会为你工作。

String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this); 
于 2013-08-31T12:19:14.700 回答