【问题标题】:ImageIcon not displayed after creating jar创建jar后不显示ImageIcon
【发布时间】:2021-01-03 17:32:40
【问题描述】:

我正在尝试用 java 做一个小项目,但没有运气 如果我用 eclipse 编译程序一切都很好,但是当我创建 jar 文件时,我得到一个空白窗口

这是我声明的图片:

public ImageIcon BACKGROUND = new ImageIcon() ;

我尝试做以下事情:

1.

new ImageIcon("Images/wood.jpg").getImage());

2.

this.BACKGROUND.setImage(Toolkit.getDefaultToolkit().getImage("Images/wood.jpg"));

3.

this.BACKGROUND = new ImageIcon(getClass().getResource("Images/wood.jpg"));

4.

/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
                                           String description) {

    java.net.URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL, description);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}

1 & 2 显示编译后的图像,3 & 4 返回 null

另一个想法是我使用的是 mac,当我使用 windows 时,编译后没有显示图像。

【问题讨论】:

  • 您是否将图像作为资源包含在 jar 文件本身中?如果没有,您可能应该这样做。

标签: java


【解决方案1】:

如果有帮助,这里有一个小的working example

public class ImageIconApplet extends JApplet {
    public void init() {
        URL url = getClass().getResource("/images/WhiteFang34.jpg");
        ImageIcon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon, JLabel.CENTER);
        add(label);
    }
}

该页面上小程序的jar 包含两个文件:

/com/whitefang34/ImageIconApplet.class
/images/WhiteFang34.jpg

我不确定您是在部署小程序还是桌面 Swing 应用程序,但是加载图像的代码和打包要求是相同的。

【讨论】:

    【解决方案2】:

    我有事……

    ImageIcon icon = new ImageIcon(getClass().getResource("/package/image.png"));
    JFrame.setIconImage(icon.getImage());
    

    把它放在你的构造函数中。

    【讨论】:

      【解决方案3】:

      您确定 Images/wood.jpg 存在于 .jar 文件中吗?

      我建议你解压缩 jar 文件并确保它在那里。否则,您将不得不修改构建 jar 的构建脚本(或您使用的任何技术)。

      相关问题:

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-10
      • 2012-06-08
      • 2015-10-08
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 2017-08-25
      • 2015-07-31
      相关资源
      最近更新 更多