问题
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.
I already tried the (java -jar MyJar.jar) to get the log but it says "Unnable to access the jar file"
I think the problem is because of this:
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.
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?
(This is what i have on my JLabels)
JLabel lblImgLogin = new JLabel(logoOne);
UPDATE
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);
Same problem, Works on eclipse but not working when exported to runnable jar file
回答1:
This one is correct:

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;
}
}
}


回答2:
Create a folder name 'Resources'(exactly this name). Now keep the logo.png in the Resources folder. Now use code as following.
ImageIcon imageIcon = new ImageIcon(getClass().getResource("/Resources/logo.png"))
Compile and build jar (Use 'package required libraries for generated jar' for Eclipse export). If after extractions of the jar, you get the Resources folder and files under it, then hopefully it will work. Sorry for my bad English
来源:https://stackoverflow.com/questions/28452508/java-project-working-on-eclipse-but-not-working-when-exported-to-runnable-jar-fi