How To: Use Images In Jarred Applets

Java textbook methods for adding images to applets usually do not take into consideration the use of jars to publish the applets. This is probably because it is a difficult subject, and because the Netscape browser has a hard time finding image files in jars, using the normal Java techniques. So here's an example of how to use images in jarred applets, so that the applets work in both Internet Explorer and in Netscape:


package myApplets;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class ImageApplet extends Applet
{
  private Image x;
  private Image o;

  public void init()
  {
    x = getImage("x.gif");
    o = getImage("o.gif");
  }

  public void paint(Graphics g)
  {
    g.drawImage(x, 0, 0, null);
    g.drawImage(o, 30, 30, null);
  }

  // loads images from jar in
  // both IE and Netscape
  // thanks to gamebrew.com
  private Image getImage(String f)
  {
    Image img = null;
    try
    {
      java.io.DataInputStream in =
        new java.io.DataInputStream(
          getClass().getResourceAsStream(f));
      byte[] data = new byte[in.available()];
      in.readFully(data);
      in.close();
      img = Toolkit.getDefaultToolkit().createImage(data);
    }
    catch(Exception e){img = getImage(getCodeBase(), f);}

    MediaTracker mt = new MediaTracker(this);
    mt.addImage(img, 0);
    try{mt.waitForID(0);}
    catch(InterruptedException e){}

    return img;
  }
}

In the above code, it is assumed that the image files are stored in the myApplets folder (i.e., in the same place that the applet's .java and .class files are stored). Here are the compilation and jarring steps:

  javac myApplets\ImageApplet.java

  jar cf myApplets.jar myApplets\*.*


Here is a simple HTML file containing the applet:

<html>
 <head>
  <title>
   An X and an O
  </title>
 </head>
 <body>
 <applet code="myApplets.ImageApplet.class"
  archive="myApplets.jar" width="100" height="100">
  Sorry, you need a Java-enabled browser to view this page.
 </applet>
 </body>
</html>



Sorry, you need a Java-enabled browser to view this page.