Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 25: Images 783


Cell Animation


Now that we have presented an overview of the image APIs, we can put together an interesting
applet that will display a sequence of animation cells. The animation cells are taken from a
single image that can arrange the cells in a grid specified via therowsandcols<param>
tags. Each cell in the image is snipped out in a way similar to that used in theTileImage
example earlier. We obtain the sequence in which to display the cells from thesequence
<param> tag. This is a comma-separated list of cell numbers that is zero-based and proceeds
across the grid from left to right, top to bottom.
Once the applet has parsed the <param> tags and loaded the source image, it cuts the
image into a number of small subimages. Then, a thread is started that causes the images
to be displayed according to the order described insequence. The thread sleeps for enough
time to maintain theframerate. Here is the source code:

/ Animation example.
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.util.*;

public class Animation extends Applet implements Runnable {
Image cell[];
final int MAXSEQ = 64;
int sequence[];
int nseq;
int idx;
int framerate;
boolean stopFlag;

private int intDef(String s, int def) {
int n = def;
if (s != null)
try {
n = Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("Number Format Exception");
}
return n;
}

public void init() {
framerate = intDef(getParameter("framerate"), 5);
int tilex = intDef(getParameter("cols"), 1);
int tiley = intDef(getParameter("rows"), 1);
cell = new Image[tilex*tiley];

StringTokenizer st = new
StringTokenizer(getParameter("sequence"), ",");
sequence = new int[MAXSEQ];
Free download pdf