Advanced Animation

Way back in Example 12-4, we saw a simple animation technique that suffered, unfortunately, from flickering. Example 12-19 is a program that performs a more graphics-intensive animation but doesn’t flicker, because it uses a technique known as double-buffering : it draws each frame of the animation off-screen, then copies the frame onto the screen all at once. This example also has better performance because it requests redraws of only the relatively small portion of the screen that needs to be redrawn.

Another interesting feature of this example is its use of the javax.swing.Timer class to call the actionPerformed( ) method of a specified ActionListener object at specified intervals. The Timer class is used here so that you don’t have to create a Thread. (Note that Java 1.3 includes java.util.Timer, a class that is similar to, but quite distinct from, javax.swing.Timer.)

Example 12-19. Hypnosis.java

package je3.graphics; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; import javax.swing.Timer; // Import explicitly because of java.util.Timer /** * A Swing component that smoothly animates a spiral in a hypnotic way. **/ public class Hypnosis extends JComponent implements ActionListener { double x, y; // The center of the spiral double r1, r2; // The inner and outer radii of the spiral double a1, a2; // The start and end angles of the spiral double deltaA; // How much the angle changes in each frame double deltaX, deltaY; ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.