Animating an Array of Images in an Applet - Java Applet

Java examples for Applet:Applet Creation

Description

Animating an Array of Images in an Applet

Demo Code

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;

class AnimApplet extends Applet implements Runnable {
  Image[] images = new Image[2];
  int frame = 0;/*from   w w  w.  java  2  s .  c  o m*/
  volatile Thread thread;

  public void init() {
    images[0] = getImage(getDocumentBase(), "http://hostname/image0.gif");
    images[1] = getImage(getDocumentBase(), "http://hostname/image1.gif");
  }

  public void start() {
    (thread = new Thread(this)).start();
  }

  public void stop() {
    thread = null;
  }

  public void paint(Graphics g) {
    g.drawImage(images[frame], 0, 0, this);
  }

  public void run() {
    int delay = 1000; // 1 second
    try {
      while (thread == Thread.currentThread()) {
        frame = (frame + 1) % images.length;
        repaint();
        Thread.sleep(delay);
      }
    } catch (Exception e) {
    }
  }
}

Related Tutorials