Java Reference
In-Depth Information
Solution
Use a background thread to drive the animation.
Discussion
One common use of threads is an animator, a class that displays a moving image. This “an-
imator” program does just that. It draws a graphical image (see
Drawing an Image
) at loca-
tions around the screen; the location is updated and redrawn from a
Thread
for each such im-
age. This version is an applet, so we see it here in the AppletViewer (
Figure 22-1
).
Figure 22-1. Animator
main program.
Example 22-5. threads/Sprite.java (part of animator program)
/** A Sprite is one Image that moves around the screen on its own */
public
public class
class
Sprite
Sprite
extends
extends
Component
implements
implements
Runnable
{
protected
protected static
static
int
int
spriteNumber
=
0
;
protected
protected
Thread t
;
protected
protected
int
int
x
,
y
;
protected
protected
Component parent
;
protected
protected
Image img
;