我正在使用 Eclipse,我希望将“img”源文件夹中的一些图像与我的 .jar 一起导出,以便它们显示在 JAR 中。
我的继承权是:
Project>src>Package>FILE.java
然后在项目中是另一个源文件夹,名为:
img>IMAGE.png
我目前使用以下方式链接到图像:
lblNewLabel_1.setIcon(new ImageIcon("img/logo1.png"));
在我导出它之前,效果很好。
我将其导出为可运行的 JAR 文件,并勾选了提取所需的库
,因为中间的文件不允许打开 .jar。提取允许其打开,但图像不显示。
最佳答案
当您在 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;
}
}
关于java - 使用我的 JAR 文件导出图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9749668/