问题
I'd like to load an image to my program, but in away that my runnable jar will also be able to do so.
So new ImageIcon(URL);
to JLabel
doesn't really work.
All my java files are in src folder, in core
package. I'd like to put my picture to src folder, but inside images
package.
Is that possible, or do I have to put my image to specific location inside my project?
And what would be a way to load image into my program so it works inside a runnable jar?
回答1:
The way I usually embed imagery inside Java Jar files is I have a package in my src
folder that contains all of my image files plus a single class called Resource
. The class code is similar to the following:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class Resource{
public static BufferedImage loadImage(String imageFileName){
URL url = Resource.class.getResource(imageFileName);
if(url == null) return null;
try {
return ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static ImageIcon loadIcon(String imageFileName){
BufferedImage i = loadImage(imageFileName);
if(i == null) return null;
return new ImageIcon(i);
}
}
Provided the Resource
class and all of your image files reside in the same package, all you have to do is create a new JLabel
with the ImageIcon
returned by calling loadIcon([simple filename])
. This will work regardless of whether you're running in an IDE or from a Jar file.
来源:https://stackoverflow.com/questions/12290265/load-image-to-program-to-work-with-jar