FileDocCategorySizeDatePackage
Animator.javaAPI DocExample2015Sat Sep 09 20:32:10 BST 2000None

Animator.java

import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;

public class Animator extends Applet 
 implements Runnable, MouseListener {

  boolean running = false;
  int thisCell = 0;
  Vector cells = new Vector();

  public void init() {

    this.addMouseListener(this);
    
    String nextCell;
    MediaTracker theTracker = new MediaTracker(this);
    for (int i = 0; (nextCell = this.getParameter("Cell" + i)) != null ; i++) {
      Image img = this.getImage(this.getDocumentBase(), nextCell);
      cells.addElement(img);
      theTracker.addImage(img, i);
      // start loading the image in a separate thread
      theTracker.checkID(i, true);
    }
    
    // wait for all images to finish loading
    try {
      theTracker.waitForAll();
    }
    catch (InterruptedException e) {      
    }
    
  }
  
  
  public void run() {
  
    for (thisCell=0; thisCell < cells.size(); thisCell++) { 
      if (!running) return;
        // paint the cell
        this.repaint();
        // sleep for a tenth of a second
        // i.e. play ten frames a second
      try {
        Thread.sleep(100);
      }
      catch (InterruptedException ie) {      
      }
    }
  
  }

  public void stop() {
    this.running = false;
  }
  
  public void start() {
    this.running = true;
    Thread play = new Thread(this);
    play.start();
  }

  public void paint(Graphics g) {
    g.drawImage((Image) cells.elementAt(thisCell), 0, 0, this);    
  }
  
  // The convention is that a mouseClick starts
  // a stopped applet and stops a running applet.
  public void mouseClicked(MouseEvent e) {
  
    if (running) {
      this.stop();
    }
    else {
      this.start();
    }
          
  }
  
  public void mousePressed(MouseEvent e) {}
  public void mouseReleased(MouseEvent e) {}
  public void mouseEntered(MouseEvent e) {}
  public void mouseExited(MouseEvent e) {}

}