// This example is from the book _Java in a Nutshell_ by David Flanagan. // Written by David Flanagan. Copyright (c) 1996 O'Reilly & Associates. // You may study, use, modify, and distribute this example for any purpose. // This example is provided WITHOUT WARRANTY either expressed or implied. /** * This applet displays an animation. It doesn't handle errors while * loading images. It doesn't wait for all images to be loaded before * starting the animation. These problems will be addressed later. **/ import java.applet.*; import java.awt.*; import java.net.*; import java.util.*; public class Animator extends Applet implements Runnable { protected Image[] images; protected int current_image; // Read the basename and num_images 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. public void init() { String basename = this.getParameter("basename"); int num_images; try { num_images = Integer.parseInt(this.getParameter("num_images")); } catch (NumberFormatException e) { num_images = 0; } images = new Image[num_images ]; for(int i = 0; i < num_images; i++) { images[i] = this.getImage(this.getDocumentBase(), basename + i +".gif"); } } // This is the thread that runs the animation, and the methods // that start it and stop it. private Thread animator_thread = null; public void start() { if (animator_thread == null) { animator_thread = new Thread(this); animator_thread.start(); } } public void stop() { if ((animator_thread != null) && animator_thread.isAlive()) animator_thread.stop(); // We do this so the garbage collector can reclaim the Thread object. // Otherwise it might sit around in the Web browser for a long time. animator_thread = null; } // This is the body of the thread--the method that does the animation. public void run() { while(true) { if (++current_image >= images.length) current_image = 0; this.getGraphics().drawImage(images[current_image], 0, 0, this); this.getToolkit().sync(); // Force it to be drawn *now*. try { Thread.sleep(200); } catch (InterruptedException e) { ; } } } }