问题
Picture inside .jar file wont work when I export it.
I made a Java program that displays a picture, and it works perfectly in Eclipse, but when I export it to a .jar file, it wont display the picture. I just started learning Java, and I have no experience with creating Jar files and using files from inside the jar file.
Heres my code:
import javax.swing.*;
class displayPicture{
public static void main(String args[]){
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("src/img.gif");
JLabel label = new JLabel(icon);
//Create the frame
frame.add(label);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
It shows the picture when I run it in Eclipse, but when I export it to a .jar file, it just shows a blank window.
回答1:
Two things...
First
The path src
is unlikely to exist once the code is build
Second
ImageIcon(String)
assumes the String
reference is a reference to a file on the file system. Resources stored within the context of the application are not files and are treated differently. They are commonly known as embedded resources.
Instead, try using ImageIcon icon = new ImageIcon(displayPicture.class.getResource("img.gif"));
or ImageIcon icon = new ImageIcon(displayPicture.class.getResource("/img.gif"));
I prefer to use ImageIO.read
as it throws an IOException
when something goes wrong and supports more file formats.
See Reading/Loading an Image for more details.
You should also take the time to have a read through Code Conventions for the Java Programming Language and Initial Threads
来源:https://stackoverflow.com/questions/22468906/picture-inside-jar-file-wont-work-when-i-export-it