【发布时间】:2015-04-11 17:09:59
【问题描述】:
我在将我的 java 文件导出到可运行的 jar 文件时遇到问题。 在eclipse中它工作正常,但是当我导出它时,它就不起作用了。
我已经尝试过 (java -jar MyJar.jar) 来获取日志,但它说 “无法访问 jar 文件”
我认为问题是因为这个:
java.net.URL logoOneUrl = getClass().getResource("/logo.png"); //already tried without the "/" and it doesn't work withouth the "/"
Icon logoOne = new ImageIcon(logoOneUrl)
因为当我将它放在评论 // 中时,当我导出它时它运行但没有图像。
我也尝试过这种方式:
java.net.URL logoScience = getClassLoader().getResource("logo.png"); 但它也不起作用。
我究竟做错了什么?
如何在 JLabel 上导出带有图像的可运行 jar 文件?
(这是我的 JLabels 上的内容)
JLabel lblImgLogin = new JLabel(logoOne);
更新
ImageIcon icon = createImageIcon("/logo.png","a pretty but meaningless splat");
protected ImageIcon createImageIcon(String path,String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
} return null;
}
JLabel lblImgLogin = new JLabel(icon);
同样的问题,在 eclipse 上工作,但导出到可运行的 jar 文件时不工作
【问题讨论】:
-
文件在你的项目中的什么位置?
-
“无法访问 jar 文件”与代码没有太大关系。这与当前目录中不存在 jar 文件 MyJar.jar 的事实有关。
-
@JBNizet 但是如果他把图像取出来,为什么它会起作用?
-
@LiamdeHaas 我在 java 文件和 src 文件中的资源上得到了图像
-
用可以读取zip文件的软件打开jar文件能看到图片吗?即 WinRAR、7zip 或解压缩。