Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Displaying a Moving Image with Animation

Problem

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

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 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).

Animator

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 = ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata