How do I load an image in a Swing application?

Scott Stanchfield

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

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

The getResource() call would look for the image as

my/funky/stuff/mypic.gif

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

URL picURL = getClass().getResource("/mypic.gif");

however, be aware that the image could then conflict with other images on the CLASSPATH. (I don't recommend using the "/" because of this).

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact