How To: Use Images In Jarred Applications

Java textbook methods for adding images to applications usually do not take into consideration the use of jars to publish the applications. Here's an example of how to extend a Panel or JPanel so that you can use images in jarred applications:


package myApps;

import java.net.*;
import java.awt.*;
import javax.swing.*;

public class JImagePanel extends JPanel
{
  private Image x;
  private Image o;

  // constructor
  public JImagePanel()
  {
    // attach the images
    Toolkit t = Toolkit.getDefaultToolkit();
    x = t.getImage(getClass().getResource("x.gif"));
    o = t.getImage(getClass().getResource("o.gif"));
  }

  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    // paint the images
    g.drawImage(x, 10, 10, null);
    g.drawImage(o, 40, 40, null);
  }
}

...or for extends Panel, it's paint instead of paintComponent

In the above code, it is assumed that the image files are stored in the myApps folder (i.e., in the same place that the application's .java and .class files are stored).



Or you can use the same approach to draw an image to any on-screen display or printed page that uses a Graphics object:

  // declare one or more member objects...
  private Image x; // stores x.gif
  private Image o; // stores o.gif

  ...in the constructor...
    // attach the images
    Toolkit t = Toolkit.getDefaultToolkit();
    x = t.getImage(getClass().getResource("x.gif"));
    o = t.getImage(getClass().getResource("o.gif"));

  ...in the paint or print method...
    g.drawImage(x, 10, 10, null);
    g.drawImage(o, 40, 40, null);