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\*.*
<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>