在jar文件中显示图像

时间:2014-05-27 20:22:04

标签: java eclipse jar resources

我知道之前已经问过这个问题,但是我已经找到了我能找到的所有解决方案,并且不能让它们为我工作。我在Eclipse中有一个程序,我试图导出到可执行jar文件。这是我第一次这样做。当我执行jar时,我的程序图像不会显示。所以我做了一些研究,发现我需要将它们作为资源加载,但我似乎无法使它工作。

这是我用来加载没有jar的图像的代码:

private void initComponents()
{

    // create an enterprise icon and make it invisible
    enterpriseIcon = new JLabel(new ImageIcon("res/enterprise1.png"));
    enterpriseIcon.setVisible(false);
}

我将所有图像放在我的根项目目录中名为res的文件夹中,并告诉Eclipse将此文件夹放在构建路径中。

当运行jar文件时图像不显示时,我尝试了以下操作:

enterpriseIcon = new JLabel(new ImageIcon(getClass().getResource("/res/enterprise1.png")));

  enterpriseIcon = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/res/enterprise.png"))));

但是,当从Eclipse中运行其中任何一个时,我得到一个空指针异常。 (我还尝试了其他一些事情,但以上是我认为我理解的唯一解决方案。)

任何有助于此工作的帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

使用Class#getResource获取jar文件中图像的URL

enterpriseIcon = new JLabel(new ImageIcon(getClass().getResource("/res/enterprise1.png")));

答案 1 :(得分:0)

试试这个。这适合我:)

private void initComponents() {
    try {
        BufferedImage icon = ImageIO.read(getClass().getResource("/enterprise1.png"));
        frame.setIconImage(icon);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

答案 2 :(得分:0)

直到昨天我也面临同样的问题。我已经解决了这个问题。让我与你分享。

  • 在Eclipse中,转到项目名称。
  • 正确的项目名称。
  • 新 - >源文件/文件夹
  • 将此源文件/文件夹命名为images
  • 现在,在本地计算机上,转到项目所在的Eclipse工作区 实际存在。
  • 将所有图像复制到新创建的图像中 '图像'文件夹就在那里。
  • 现在回到Eclipse。
  • 右键点击您的项目 - >刷新
  • 现在,无论您在.java文件中使用图像,请转到这些行并在图像位置前加上images /

示例:XXX xxx = XXXX(example.jpg) 改变它.... XXX xxx = XXXX(images / example.jpg)

BOOM !! 运行.jar文件时将显示图像。

注意:请勿使用java -jar AppName.jar从cmd运行.jar文件 相反,只需双击.jar文件,您就会看到图像。

如果它对你有用,请亲自投票。 :)