xhtml
 

Images

The ImageIcon class forms a graphics component containing a gif, jpeg or png image from a file.  You might be tempted to load the image straight from a file with something like:

      ImageIcon = new ImageIcon("images/logo.gif");

This asks for the image file to be loaded from the images subdirectory of the "current directory".  If you later collect all your files into a jar file so that the program can be distributed and run by other people, this won't work.  When someone else runs the program, the "current directory" may have the jar file in it (though you can't even be sure of that), but it won't directly contain the images subdirectory.

A much better bet is to say: "get the image file from the same place you got this class".  Here is a simple example of how to do that:

FramedLogo.java     logo.gif
...
import java.net.*;
...
      URL address = FramedLogo.class.getResource("images/logo.gif");
      ImageIcon image = new ImageIcon(address);
      JLabel icon = new JLabel(image);
      frame.add(icon);
...

The java.net package needs to be imported to support the URL class.  The getResource method looks for the image file in the same place as the FramedLogo.class file, or whatever class you specify.  The path argument always uses forward slashes, because it gets converted into a URL (perhaps a file: URL).  An ImageIcon is not itself a graphics component, so it is wrapped in a JLabel.


Back