1  /*
  2   *  File:  MovingSquare.java
  3   *
  4   *  A moving square with boundary checking
  5   *
  6   *  Copyright:  Northeast Parallel Architectures Center
  7   *
  8   */
  9  
 10  import java.applet.Applet;
 11  import java.awt.*;
 12  
 13  public class MovingSquare extends Applet implements Runnable {
 14  
 15    // A reference to a square:
 16    private Square square;
 17    
 18    // Override java.applet.Applet.init:
 19    public void init () {
 20  
 21      setBackground( Color.black );
 22      setForeground( Color.white );
 23      
 24      // Instantiate a square:
 25      square = new Square( 75, 25, 50 );
 26      square.setColor( Color.red );
 27      
 28    }
 29  
 30    // A thread of execution:
 31    private Thread thread;
 32      
 33    // Override java.applet.Applet.start:
 34    public void start() {
 35      if ( thread == null ) {
 36        thread = new Thread( this );
 37        thread.start();
 38      }
 39    }
 40    
 41    // Override java.applet.Applet.stop:
 42    public void stop() {
 43      if ( thread != null ) {
 44        thread.stop();
 45        thread = null;
 46      }
 47    }
 48    
 49    // Implement java.lang.Runnable.run:
 50    public void run() {
 51      while ( thread != null ) {
 52        try {
 53          Thread.sleep( 20 );
 54        } catch ( InterruptedException e ) {
 55          // do nothing   
 56        }
 57        repaint();
 58      }
 59    }
 60  
 61    // Initially, the square moves two pixels down and to the right:
 62    int dx = 2, dy = 2;
 63    
 64    // Override java.awt.Component.paint:
 65    public void paint( Graphics g ) {
 66    
 67      // Check if square is out of bounds:
 68      checkBounds( this.getBounds() );
 69      
 70      // Move and fill the square:
 71      square.translate( dx, dy );
 72      square.fill( g );
 73      
 74    }
 75    
 76    private void checkBounds( java.awt.Rectangle r ) {
 77  
 78      // Get the bounding box of the square:
 79      java.awt.Rectangle bb = square.getBounds();
 80  
 81      // Compute the dimensions of the square:
 82      int w = bb.width, h = bb.height;
 83      int new_x = bb.x + dx, new_y = bb.y + dy;
 84      
 85      // If the square is out of bounds, reverse direction:
 86      if ( ( new_x < r.x ) || ( new_x + w > r.x + r.width ) )  dx *= -1;
 87      if ( ( new_y < r.y ) || ( new_y + h > r.y + r.height ) )  dy *= -1;
 88  
 89    }
 90  
 91  }