CHAPTER 10 ■ ANIMATION
animationThread = new Thread(scootBallPanel);
scootBallPanel.setAnimating(true);
animationThread.start();
}
}
}
The key to the this class is the actionPerformed method. It checks for which action the user has
chosen and starts the animation if the user selects the Scoot button (and if the ball isn't already being
drawn). The animation is accomplished through the ScootBallPanel class. Because ScootBallPanel
implements the Runnable interface (meaning it can be run in its own thread), we have a means to let it
know when to start drawing the ball. Note that we create a new thread each time the Scoot button is
pressed, letting any previous thread go to garbage collection. That's a simple way to restart an animation
process.Listing 10-2 shows the ScootBallPanel class.
Listing 10-2. The ScootBallPanel class
package com.bryantcs.examples.animation;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class ScootBallPanel extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private boolean animating = false;
private int xPosition = 5;
public boolean isAnimating() {
return animating;
}
public void setAnimating(boolean animating) {
this.animating = animating;
}
public void reset() {
xPosition = 5;
}
public void paint (Graphics g) {
int width = this.getSize().width;
int height = this.getSize().height;
super.paintComponent(g);