CHAPTER 10 ■ ANIMATION
The heart of the ScootBallPanel class is the run method, which implements the corresponding run
method in the Runnable interface. All it does is run through a continuous loop, sleeping a while and then
repainting the panel. How long it sleeps dictates the frame rate. In this case, it sleeps for 40 milliseconds,
producing a frame rate of about 25. I wrote, “about,” because the repainting takes some time, yielding a
frame rate a bit less than 25. We see how to get a more exact frame rate in the next example.
The paint method draws the ball on the screen, each time at a new position, until that position
exceeds the width of the panel. In particular, the call to super.paintComponent(g) redraws the panel to its
original state (a blank white box). The remaining lines then draw the ball. Figure 10-2 shows a ball
scooting across the screen.
Figure 10-2. Scootball in actionScootball is not much of a program, but it demonstrates the basics of
animation: drawing an updated image every so often (generally some number of times per second). Let's
move on to a slightly more complicated (and thus more interesting) example.
Animating Multiple Items
This example shows one way to animate multiple items at once. In this case, we use an object-oriented
approach to the problem (Java is an object-oriented language, after all). In particular, we create a class
for the things we want to animate and then create multiple instances of that class. Being a simple
example, we use the same class for all the animating items. However, you can use the same technique to
animate different kinds of objects. For example, a tank (an instance of one class) might shoot a bullet (an
instance of a different class) at a bunker (an instance of a third class).
The trick is to have each object draw itself and then iterate through them, letting each one draw
itself in turn. In that way, the calling class needs to know nothing about how to draw the objects and can
focus on the timing and user interface. This kind of organization embodies one of the principles of