我正在使用Eclipse,我希望将“img”源文件夹中的一些图像与我的.jar一起导出,以便它们显示在JAR中。
我的Heirarchy是:
项目> SRC>包装及GT; FILE.java
然后在project中是另一个名为:
的源文件夹IMG> IMAGE.png
我目前正在使用以下链接到图片:
lblNewLabel_1.setIcon(new ImageIcon("img/logo1.png"));
这很好,直到我导出它。
我将其导出为带有Extract required libraries
的Runnable JAR文件,因为中间的文件不允许打开.jar。提取允许它打开,但图像不显示。
答案 0 :(得分: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;
}
}