/////// Animator.java /////// import java.applet.Applet; import java.awt.*; import java.net.URL; import java.awt.event.*; // This is an applet-application dual purpose program // for general animation // improve init so parameters are set with PARAM // or on the command line public class Animator extends Applet implements Runnable { public void init() { codeBase = getDocumentBase(); init2(); } public void init2() { nf = 10; fps = 16; filename = "images/T"; extension = ".gif"; interval = 1000/fps; img = new ImageSequence(codeBase, filename, extension, nf, this, tk); addMouseListener(new MouseHandler()); } // starts the animation thread public void start() { if ( ant == null ) { ant = new Thread(this); ant.start(); // thread start } } // stops the animation thread public void stop() { ant = null; } // mouse click handler public void beginEnd() { if ( ant == null ) start(); else stop(); } public void run() { long t0; Thread me = Thread.currentThread(); int n = times; while (ant == me) { t0 = System.currentTimeMillis(); try { frame = img.next(nonstop); if ( ! nonstop && ! img.ERROR && frame == null ) { if ( --n > 0 ) frame = img.next(nonstop); else break; } repaint(); t0 += interval; Thread.sleep(Math.max(0, t0-System.currentTimeMillis())); } catch (InterruptedException e) { break; } } ant = null; } public void setTimes(int i) { if ( i > 0 ) { nonstop = false; times = i; } else if ( i == 0 ) nonstop = true; } public void update(Graphics g) { int w = getSize().width, h = getSize().height; if ( frame != null ) // draws a frame g.drawImage(frame, 0, 0, w, h, Color.white, this); else // image not ready or error { g.drawRect(0, 0, w, h); if ( img.ERROR ) g.drawString("Error loading images!", 0, h/2); } } public void paint(Graphics g) { update(g); } private final class MouseHandler extends MouseAdapter { public void mouseClicked(MouseEvent e) { beginEnd(); } } protected URL codeBase=null; // applet codebase protected Thread ant; // the animation thread protected Image frame=null; // current frame protected ImageSequence img; // image manager protected boolean nonstop =false; // continuous loop or not protected int times = 1; // show one or more times protected int nf; // number of frames protected int fps; // frames per second protected int interval=0; // time interval of a frame protected String filename, extension; // image files protected static Toolkit tk = null; // local image loader public static void main(String[] args) { Animator an = new Animator(); tk = Toolkit.getDefaultToolkit(); an.init2(); Frame win = new Frame("Animation"); win.add(an, "Center"); win.setSize(an.img.width(), an.img.height()); an.start(); win.setVisible(true); } }