ImageAnimatorpublic class ImageAnimator extends Applet implements RunnableThis applet displays an image animation. It uses the MediaTracker class
to load the images and verify that there are no errors. |
Fields Summary |
---|
protected int | num_frames | protected Image[] | frames | protected int | framenum | protected MediaTracker | tracker | protected Thread | animator_thread |
Methods Summary |
---|
public void | init()Read the basename and num_frames parameters.
Then read in the images, using the specified base name.
For example, if basename is images/anim, read images/anim0,
images/anim1, etc. These are relative to the current document URL. // The thread for animation
String basename = this.getParameter("basename");
try { num_frames = Integer.parseInt(this.getParameter("num_frames")); }
catch (NumberFormatException e) { num_frames = 0; }
// getImage() creates an Image object from a URL specification,
// but it doesn't actually load the images; that is done asynchronously.
// Store all the images in a MediaTracker so we can block until
// they have all loaded. This method must return promptly, so we don't
// wait for them to load here.
tracker = new MediaTracker(this);
frames = new Image[num_frames];
for(int i = 0; i < num_frames; i++) {
frames[i] = this.getImage(this.getDocumentBase(), basename+i);
tracker.addImage(frames[i], i); // Add image to tracker, assigning an ID
}
| public void | paint(java.awt.Graphics g)Draw the current frame of the animation g.drawImage(frames[framenum], 0, 0, this);
| public void | run()This is the body of the thread--the method that does the animation.
// First, wait until all images have loaded completely.
for (int i = 0; i < num_frames; i++) {
this.showStatus("Loading frame: " + i);
// Block until the specified image is loaded. The ID argument is the
// one we passed to addImage().
try { tracker.waitForID(i); } catch (InterruptedException e) {;}
// Check for errors loading it. Display an error message if necessary
if (tracker.isErrorID(i)) {
this.showStatus("Error loading frame " + i + "; quitting.");
return;
}
}
this.showStatus("Loading frames: done."); // Done loading all frames
// Now do the animation: increment the framenumber, redraw, pause
while(true) {
if (++framenum >= frames.length) framenum = 0;
repaint();
try { Thread.sleep(200); } catch (InterruptedException e) { ; }
}
| public void | start()Create the animation thread and start it running
if (animator_thread == null) {
animator_thread = new Thread(this);
animator_thread.start();
}
| public void | stop()Stop the animation thread
if ((animator_thread != null) && animator_thread.isAlive())
animator_thread.stop();
animator_thread = null;
| public void | update(java.awt.Graphics g)Don't clear the screen before calling paint() paint(g);
|
|