Writing a Java Applet
Create an applet that will run in a Java compatible web browser by
subclassing the java.applet.Applet superclass. Using what you know
about threads, launch an animation thread that will display itself in
the browser without blocking user input from the keyboard and
mouse. Have the animation pause and unpause with a mouse click or
accept some other kinds of input. In terms of design, you may want to
create a general Animation class as either an abstract class and have
the Animator applet instantiate a subcalss of that. This way, the
various implementations of Animation can be swapped in without
altering the Animator applet.
For example:
abstract class Animation
{
...
public abstract void drawNextFrame(Graphics g);
...
}
public class Animator extends Applet implements Runnable
{
private Animation animation_;
private Image image_buffer_;
private boolean thread_alive_;
...
public void run()
{
...
Graphics g = image_buffer_.getGraphics();
while (thread_alive_)
{
animation_.drawNextFrame(g);
Thread.sleep(100);
}
...
}
}
To really improve the visual quality of the animation, use a technique
called Double Buffering. Instead of drawing the animation frame
directly to the screen, draw to an offscreen image and then display
the entire image at once. When making multiple graphics method calls
on the display, a viewer may notice the drawing process. If the
drawing process is hidden from the user, the transition between frames
appears much smoother.
View the
applet.
Script to run the Applet demo
References
Flanagan, David; Java in a Nutshell, Sections 4 and 8 on Applets and Advanced Graphics
The Java tutorial is a
useful online resource, especially the chapters on
writing applets and performing
animation.
Look at the Javasoft Java API Documentation on the
java.applet package.