运行从 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));
And:
try
{
label.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/resources/header.jpg"))));
}
catch (IOException e1)
{
e1.printStackTrace();
}
有什么建议么?
对我来说效果很好。检查一下您可能有什么不同。
示例1:(资源in src)
Steps:
-
文件结构
-
Code
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);
}
});
}
}
-
[右键单击项目] → [导出] → [可运行 Jar 文件] → [设置启动配置]
-
Profit
仅供参考,相同的设置在 eclipse 中运行也很好
示例2:(资源not在 src 中 - 但在项目中)
Steps:
-
文件结构(注意资源看起来像一个普通文件夹)
-
我们现在要做的就是将资源放在构建路径上。其作用是将文件夹中的所有内容(不包括文件夹本身)放在类路径上
-
新代码不再使用路径的资源前缀
URL url = Main.class.getResource("/stackoverflow.png");
与上面的步骤 3 和 4 相同,然后盈利!
UPDATE
设置启动配置
一般来说,一旦运行类(即右键单击类并作为 Java 应用程序运行),就会设置运行配置。您需要将其设置为清单中的启动点。但以下是手动执行此操作的方法。
Steps:
-
[右键单击项目]→[属性]→[运行/调试设置]
You can see that I already have a run configruation (that is implicitly set from simply running the class). But to create a new one, select [New] → [Java Application]
-
创建运行配置的名称并浏览或键入主启动类。就我而言,它是com.stackoverflow.test.Main
class
-
现在,当您如上例所示导出时,您选择运行配置
像上面一样运行 jar。
EDIT
检查结果
显现:
Manifest-Version: 1.0
Rsrc-Class-Path: ./
Class-Path: .
Rsrc-Main-Class: com.stackoverflow.test.Main
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
提取的罐子:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)