A popular task for a thread in Java is to control an animation.
A thread process can direct the drawing of each frame while other
aspects of the interface, such as responding to user input, can
continue in parallel.
The SimpleAnimationApplet
shown below illustrates the basics of an applet animation by modifying
the colors of text in each "frame". The class implements
the Runnable
interface and the overridden run()
method contains a continuous loop for updating the display. The
sleep()
method in the Thread
class is used to pause between each frame. Here the framing is a
slow 1 per second rate.
The applet's start()
method (called when the page is loaded) creates the thread and starts
it. A flag (the thread's reference variable) is checked at the start
of each loop in to see if the process should jump from the loop
and end the thread. The applet's stop()
method (called when the browser loads another page), sets the flag
so that the looping in run()
finishes.
Note that the repaint()
method does not cause the immediate repainting of the applet component
but puts a request for repainting on the AWT's task queue. This
allows the AWT to coordinate repainting with other tasks such as
handling interface events.
|
import
java.awt.*;
/** Demo of animation a with Runnable implementation. **/
public class SimpleAnimationApplet extends java.applet.Applet
implements
Runnable {
Thread fThread;
Color [] fColorSet = {Color.RED, Color.BLUE, Color.GREEN};
Color [] fColors = new Color[3];
int fColorIndex = 0;
/** Applet's start method creates the thread and
starts it. **/
public void start () {
// Create an instance of Thread with
a
// reference to this Runnable instance.
fThread = new Thread (this);
// Start the thread
fThread.start ();
} // start
/** Use applet stop method to stop thread loop.
**/
public void stop () {
if (fThread != null) {
fThread =
null;
}
} // stop
/** Override the Runnable run() method. **/
public void run() {
while (fThread != null) {
// Rotate
colors
for (int i=0; i < 3; i++)
{
int index = fColorIndex%3;
fColors[i] = fColorSet[index];
fColorIndex++;
}
// Shift colors in next
loop.
fColorIndex += 2;
repaint();
// Pause
try {
Thread.sleep(1000);
}
catch (InterruptedException
e) {}
}
} // run
/** Paint the text. **/
public void paint(java.awt.Graphics g) {
g.setColor(fColors[0]);
g.drawString("Animation", 20, 30);
g.setColor(fColors[1]);
g.drawString("Demo", 80, 30);
g.setColor(fColors[2]);
g.drawString("Program", 120, 30);
} // paint
} // class SimpleAnimationApplet |
References & Web Resources
Last update: Oct. 14, 2005
|