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

public class BouncingBalls extends Applet {
    public static int width;
    public static int height;
    Ball b;

    public void init ( ) {
        setBackground(Color.white);
        height = getBounds().height;
        width = getBounds().width;
    } // init

    public void start ( ) {
        b = new Ball(width/2, height/2, 5, 7, Color.red);
        b.start( );
    } // start

    public void stop () {
        b.stopBall();
    } // stop
   
    public void paint (Graphics g) {
        b.paint(g);
    } 
    
    private class Ball extends Thread {

        int x, y;     // current location
        int dx, dy;   // speed
        int diameter = 10;
        Color color;
        boolean alive;

        public Ball (int x, int y, int dx, int dy, Color color) {
            this.x = x;
            this.y = y;
            this.dx = dx;
            this.dy = dy;
            this.color = color;
            alive = true;
        }

        public void move  () {
            if (x < 0 || x >= BouncingBalls.width)
                dx = - dx;
            if (y < 0 || y >= BouncingBalls.height)
                dy = - dy;
            x += dx;
            y += dy;
        }

        public void paint (Graphics g) {
            g.setColor(color);
            g.fillOval(x, y, diameter, diameter);
        }

        public synchronized void stopBall () { //substitutes stop() which is deprecated
            alive = false;
        }

        public synchronized boolean isLiving () {
            return alive;
        }
 
        public void run () {
            while  (isLiving()) {
                move();
                repaint();
                try { Thread.sleep(50);
                } catch (InterruptedException exc) { }
            }
        }


    } // Ball

} // BouncingBalls

