gpt4 book ai didi

java - Eclipse 导出的 Runnable JAR 不显示图像

转载 作者:IT老高 更新时间:2023-10-28 20:57:02 26 4
gpt4 key购买 nike

运行从 Eclipse 导出的 JAR 文件时,我的图像不会加载。

我在资源类包中有图像。我也尝试了图像源文件夹,但没有成功。

从 Eclipse 加载时可以完美运行。图像在导出的 JAR 文件中,因此可以正常导出。

我试过了:

label.setIcon(new ImageIcon(MainFrame.class.getResource("/resources/header.jpg")));

我也试过了:

URL url = getClass().getResource("/resources/header.jpg");
Image image = Toolkit.getDefaultToolkit().getImage(url);
label.setIcon(new ImageIcon(image));

还有:

try
{
label.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/resources/header.jpg"))));
}
catch (IOException e1)
{
e1.printStackTrace();
}

有什么建议吗?

最佳答案

对我来说很好用。检查您可能有什么不同。

示例1:(资源in src)

步骤:

  1. 文件结构

    enter image description here

  2. 代码

    package com.stackoverflow.test;

    import java.net.URL;
    import javax.swing.*; // Wild carded for brevity.
    // Actual code imports single classes
    public class Main {
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    URL url = Main.class.getResource(
    "/resources/stackoverflow.png");
    ImageIcon icon = new ImageIcon(url);
    JFrame frame = new JFrame();
    frame.add(new JLabel(icon));
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    }
    });
    }
    }
  3. 【右键项目】→【导出】→【Runnable Jar File】→【设置启动配置】

    enter image description here

  4. 利润

    enter image description here

仅供引用,同样的设置也可以在 eclipse 中运行


示例 2:(资源不在在 src - 但在项目中)

步骤:

  1. 文件结构(注意资源看起来像一个普通文件夹)

    enter image description here

  2. 我们现在要做的,就是把资源放到构建路径上。这样做是将所有内容放在类路径上的文件夹中(不包括文件夹本身)

    • 右击项目,进入【构建路径】→【配置构建路径】

      enter image description here

    • 从对话框中的 [Sources] 选项卡中,选择 [Add Folder],然后在新对话框中选择 [resources] 文件夹

      enter image description here

    • 现在资源文件夹的内容在构建路径中(注意文件夹中的小包

      enter image description here

  3. 新代码不再使用资源前缀作为路径

    URL url = Main.class.getResource("/stackoverflow.png");
  4. 与上面的第 3 步和第 4 步相同,并且获利!


更新

设置启动配置

通常,一旦您运行类(即右键单击类并作为 Java 应用程序运行),就会设置运行配置。您需要将其设置为 list 中的启动点。但这里是手动操作的方法。

步骤:

  1. 【右键项目】→【属性】→【运行/调试设置】

    enter image description here您可以看到我已经有一个运行配置(这是通过简单地运行类隐式设置的)。但是要创建一个新的,选择[New] → [Java Application]

  2. 为运行配置创建一个名称并浏览或键入一个主启动类。就我而言,它是 com.stackoverflow.test.Main

    enter image description here

  3. 现在如上例所示导出时,选择运行配置

    enter image description here

  4. 像上面一样运行jar。


编辑

检查结果

list :

Manifest-Version: 1.0
Rsrc-Class-Path: ./
Class-Path: .
Rsrc-Main-Class: com.stackoverflow.test.Main
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader

提取的 jar :

enter image description here

关于java - Eclipse 导出的 Runnable JAR 不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25635636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com