CHAPTER 10 ■ ANIMATION
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class MouseSpritePanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image[] spriteImages = new Image[4];
private ArrayList<MouseSprite> currentSprites = new ArrayList<MouseSprite>();
MouseSpritePanel() {
try {
spriteImages[0] = ImageIO.read(new
File("C:\\test\\sprites\\sprite1.png"));
spriteImages[1] = ImageIO.read(new
File("C:\\test\\sprites\\sprite2.png"));
spriteImages[2] = ImageIO.read(new
File("C:\\test\\sprites\\sprite3.png"));
spriteImages[3] = ImageIO.read(new
File("C:\\test\\sprites\\sprite4.png"));
} catch (IOException e) {
System.out.println("Couldn't open a sprite file");
System.exit(1);
}
}
void add (int x, int y) {
MouseSprite newSprite = new MouseSprite(x, y, spriteImages, this);
currentSprites.add(newSprite);
}
public void paint (Graphics g) {
super.paintComponent(g);
for (int i = 0; i < currentSprites.size(); i++) {
MouseSprite currentSprite = currentSprites.get(i);
if (!currentSprite.isDone()) {
currentSprite.draw(g);
} else {
currentSprite = null;
currentSprites.remove(i);
}
}
}
}
The MouseSpritePanel class manages a set of images, which it passes to each new MouseSprite
object. When each sprite is done drawing itself, the MouseSpritePanel removes the sprite object, to keep
from cluttering the list and let the finished sprite be garbage collected. Otherwise, we'd have a runaway
memory leak, which would constitute bad programming.