我在将我的 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 文件?
(这是我的 JLabel 上的内容)
JLabel lblImgLogin = new JLabel(logoOne);
更新
ImageIcon icon = createImageIcon("/logo.png","漂亮但无意义的拼音");
protected ImageIcon createImageIcon(String path,String description) {
java.net.URL imgURL = getClass().getResource(路径);
如果(imgURL!= null){
返回新的 ImageIcon(imgURL,描述);
} 别的 {
System.err.println("找不到文件:"+ path);
} 返回空值;
}
JLabel lblImgLogin = new JLabel(icon);
同样的问题,在 eclipse 上工作但在导出到可运行的 jar 文件时不工作
最佳答案
这个是正确的:
public class MainApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Testing");
ImageIcon icon = createImageIcon("/resources/logo.png");
JLabel label1 = new JLabel("Image and Text", icon, JLabel.CENTER);
//Set the position of the text, relative to the icon:
label1.setVerticalTextPosition(JLabel.BOTTOM);
label1.setHorizontalTextPosition(JLabel.CENTER);
frame.getContentPane().add(label1);
frame.pack();
frame.setVisible(true);
}
protected static ImageIcon createImageIcon(String path) {
URL imgURL = MainApp.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
关于Java 项目在 Eclipse 上工作但在导出到可运行的 jar 文件时不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28452508/