Java项目在Eclipse上工作但在导出到runnable jar文件时不起作用 [英] Java project working on Eclipse but not working when exported to runnable jar file
问题描述
我遇到了将java文件导出到runnable jar文件的问题。
在eclipse中它工作正常,但是当我导出它时,它不起作用。
i am having a issue with exporting my java file to a runnable jar file. In the eclipse it works fine, but when i exported it, it doesn't work.
我已经尝试了(java -jar MyJar.jar)得到日志,但它说
无法访问jar文件
I already tried the (java -jar MyJar.jar) to get the log but it says "Unnable to access the jar file"
我认为问题是因为:
java.net.URL logoOneUrl = getClass().getResource("/logo.png"); //already tried without the "/" and it doesn't work withouth the "/"
Icon logoOne = new ImageIcon(logoOneUrl)
因为我把它放在评论 //
当我导出它时运行但没有图像。
Because when i put it in comment //
when I exported it runs but without the image.
我也尝试过这种方式:
java.net.URL logoScience = getClassLoader()。getResource(logo.png);
但它也不起作用。
我做错了什么?
如何在JLabel上导出带有图像的可运行jar文件?
I also tried this way:
java.net.URL logoScience = getClassLoader().getResource("logo.png");
but it doesn't work too.
What am i doing wrong?
How do i export a runnable jar file with a image on a JLabel?
(这是我在JLabel上的内容)
JLabel lblImgLogin = new JLabel(logoOne);
(This is what i have on my JLabels)
JLabel lblImgLogin = new JLabel(logoOne);
更新
ImageIcon icon = createImageIcon(/ logo.png,一个漂亮但毫无意义的splat);
protected ImageIcon createImageIcon(String path,String description){
java.net.URL imgURL = getClass()。getResource(path);
if(imgURL!= null){
返回新的ImageIcon(imgURL,description);
} else {
System.err.println(找不到文件:+路径);
}返回null;
}
JLabel lblImgLogin = new JLabel(icon);
相同的问题,在Eclipse上运行但在导出到runnable jar文件时无法正常工作
Same problem, Works on eclipse but not working when exported to runnable jar file
推荐答案
这个是正确的:
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上工作但在导出到runnable jar文件时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!