How do I load an image in a Swing application?
Created May 4, 2012
The easiest way to do this is to use Swing's ImageIcon class. For example
ImageIcon i = new ImageIcon("mypic.gif");
You can then use the icon in many Swing components, like a JButton:
JButton b = new JButton(i);
Note that it's generally a good idea to use Class.getResource() to find the image file rather than directly use the file name as above. This allows you to put the image anywhere on your CLASSPATH. For example:
URL picURL = getClass().getResource("mypic.gif"); ImageIcon i = new ImageIcon(picURL);
In this case, the pic would be in the CLASSPATH under the directory structure of the current class' package. For example, if you had
The getResource() call would look for the image as
on the CLASSPATH. If you didn't want the package name prepended, you could add a "/" in front of the image file name, as in
however, be aware that the image could then conflict with other images on the CLASSPATH. (I don't recommend using the "/" because of this). package my.funky.stuff;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.net.URL;
public class SomeClass {
public SomeClass() {
URL picURL = getClass().getResource("mypic.gif");
ImageIcon i = new ImageIcon(picURL);
JButton b = new JButton(i);
}
}
my/funky/stuff/mypic.gif
URL picURL = getClass().getResource("/mypic.gif");