Displaying a Moving Image with Animation


You need to update a graphical display while other parts of the program are running.


Use a background thread to drive the animation.


One common use of threads is an animator, a class that displays a moving image. This program, Animator, does just that. To simplify, it uses a small drawn rectangle instead of a graphical image (see Section 12.7). This version is an applet, so we see it here in the AppletViewer (Figure 24-1).


Figure 24-1. Animator

Chapter 24 is the code for the Animator program.

Example 24-4. Animator.java (applet)

// graphics/Sprite.java import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; /** A Sprite is one Image that moves around the screen on its own */ class Sprite extends Component implements Runnable { protected static int spriteNumber = 0; protected Thread t; protected int x, y; protected Bounce parent; protected Image img; protected boolean done = false; /** Construct a Sprite with a Bounce parent: construct * and start a Thread to drive this Sprite. */ Sprite(Bounce parent, Image img) { super( ); this.parent = parent; this.img = img; setSize(img.getWidth(this), img.getHeight(this)); t = new Thread(this); t.setName("Sprite #" + ++spriteNumber); t.start( ); } /** Stop this Sprite's thread. */ void stop( ) { System.out.println("Stopping " + t.getName( )); done = ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.