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 {

  Ball b1, b2;
  Thread t;
  
  public void init () {
  
    b1 = new Ball(10, 32, size());
    b1.start();
    b2 = new Ball(155, 75, size());
    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 e) {      
      }
    }
    
  }


}

class Ball extends Thread {

  private Rectangle r;
  private int x_increment = 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 e) {   
      }
      
    }
    
  }

}


Previous | Next | Top
Last Modified August 4, 1999
Copyright 1997-1999 Elliotte Rusty Harold
elharo@metalab.unc.edu