【问题标题】:Exporting Images with my JAR file使用我的 JAR 文件导出图像
【发布时间】:2012-04-02 17:28:35
【问题描述】:

我正在使用 Eclipse,我希望将“img”源文件夹中的一些图像与我的 .jar 一起导出,以便它们显示在 JAR 中。

我的层次结构是:

项目>src>包>FILE.java

然后在项目中是另一个名为的源文件夹:

img>IMAGE.png

我目前正在使用链接到图片:

lblNewLabel_1.setIcon(new ImageIcon("img/logo1.png"));

这很好,直到我导出它。

我将它导出为一个可运行的 JAR 文件,并勾选了Extract required libraries,因为中间的文件不允许打开 .jar。提取允许它打开,但图像不显示。

【问题讨论】:

    标签: java eclipse image jar


    【解决方案1】:

    在 JAR 中加载数据时,路径不一样。

    您可以在从 JAR 运行时使用此方法加载图像:

    /**
      * Create an instance of ImageIcon with the given path
      * @param path  String - path of the image
      * @return  ImageIcon - ImageIcon made with the image at the given path
      */
    private ImageIcon createImageIcon(String path) {
        if (path != null) {
            URL tmp = getClass().getResource(path.replace("\\", "/"));
            if(tmp!=null)
                return new ImageIcon(tmp);
            else
                return new ImageIcon();
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
    

    【讨论】:

    • 当我这样做时,然后像这样调用它: lblNewLabel_1.setIcon(createImageIcon("logo1.png"));它不显示图像
    • Ofc,图片和你的java文件不在同一个目录下。如果你的“img”目录和你的“src”目录在同一个地方。我想你可以试试../../img/logo1.png。我不是 100% 确定你比我更了解你的文件层次结构;)
    • 不。没有。在程序中显示图像很好,除了当我导出它时,它们不再显示了。
    • lblNewLabel_1.setIcon(new ImageIcon("img/logo1.png"));显示它很好,但是当我使用它时不再显示。如何导出 img 文件夹中的图像,以便它们显示在我的可运行 jar 中?
    • 我在 jar 中使用这种方法,所以我确信它有效。我不知道您是如何创建 jar 的,但显然您给出的路径是错误的。打开你的 jar 并获取从类文件到图像文件的路径。
    猜你喜欢
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2014-04-23
    相关资源
    最近更新 更多