Multiple Independent Animations

There are times when it makes sense to have multiple animations running at once. In this case rather than implementing Runnable, you should subclass Thread. The following program demonstrates this with an applet that bounces two balls independently of each other.

import java.awt.*;
import java.applet.*;

public class TwoBall extends Applet implements Runnable {

  private Ball   b1;
  private Ball   b2;
  private Thread t;
  
  public void init () {
  
    b1 = new Ball(10, 32, this.getSize());
    b1.start();
    b2 = new Ball(155, 75, this.getSize());
    b2.start();
    t = new Thread(this);
    t.start();
     
  }
  
  
  public void paint (Graphics g) {
    g.fillOval(b1.getX(), b1.getY(), b1.getWidth(), b1.getHeight());
    g.fillOval(b2.getX(), b2.getY(), b2.getWidth(), b2.getHeight());
  }
  
  public void run() {

    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

    while (true) {  // infinite loop
      this.repaint();
      try {
        Thread.sleep(10);
      }
      catch (InterruptedException ex) {      
      }
    }
    
  }


}

class Ball extends Thread {

  private Rectangle r;
  private int deltaX = 1;
  private int deltaY = 1;
  private Dimension bounds;

  public Ball(int x, int y, Dimension d) {
    r = new Rectangle(x, y, 20, 20);
    bounds = d;
  }

  public int getX() {
    return r.x;
  }

  public int getY() {
    return r.y;
  }

  public int getHeight() {
    return r.height;
  }

  public int getWidth() {
    return r.width;
  }

  public void run() {

    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

    while (true) {  // infinite loop
      r.x += deltaX;
      r.y += deltaY;
      if (r.x + r.width >= bounds.width || r.x < 0) {
        deltaX *= -1;
      }
      if (r.y + r.height >= bounds.height || r.y < 0) {   
        deltaY *= -1;
      }
      try {
        Thread.sleep(30);
      }
      catch (InterruptedException ex) {   
      }
      
    }
    
  }

}

two bouncing balls


Previous | Next | Top | Cafe au Lait

Copyright 1997-1999, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified August 20, 2002