Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 10 ■ ANIMATION

The the MouseSprite class, shown in Listing 10-8, draws each of the four sprites in turn.
Conceptually, it is similar to the Firework class, in that it draws its pieces on the screen and then
announces that it's done, so that the class holding a reference to it can let that reference go, which lets
the system garbage collect the now useless MouseSprite object.


Listing 10-8. The MouseSprite class


package com.bryantcs.examples.animation;


import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;


import javax.swing.JPanel;


public class MouseSprite {
private int spriteX, spriteY, step;
private boolean done = false;
Image[] spriteImages= new Image[4];
JPanel spritePanel;


MouseSprite(int x, int y, Image[] images, JPanel panel) {
spriteX = x;
spriteY = y;
step = 0;
spriteImages = images;
spritePanel = panel;
}


void draw(Graphics g) {
ImageObserver observer = spritePanel;
if (step < 4) {
g.drawImage(spriteImages[step], spriteX, spriteY, observer);
step++;
} else {
done = true;
}
}


public boolean isDone() {
return done;
}


}


Figure 10-5 shows the MouseSprite program.
Free download pdf