//BouncerApplet2.java
//A Start button starts a red ball bouncing around
//within a square. Here the Ball2 class extends the
//Thread class and overrides its run() method.

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

public class BouncerApplet2 extends Applet
implements ActionListener
{
    private Button startButton;

    public void init()
    {
        startButton = new Button("Start");
        add(startButton);
        startButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event)
    {
        if (event.getSource() == startButton)
        {
            Graphics g = getGraphics();
            Ball2 ball = new Ball2(g);
            ball.start();
        }
    }
}

class Ball2 extends Thread
{
    private Graphics g;
    private int x = 7, xChange = 7;
    private int y = 0, yChange = 2;
    private int diameter = 10;
    private int rectLeftX = 0, rectRightX  = 100;
    private int rectTopY = 0,  rectBottomY = 100;

    public Ball2(Graphics graphics)
    {
        g = graphics;
    }

    public void run()
    {
        g.drawRect(rectLeftX+5, rectTopY,
                   rectRightX-rectLeftX-5,
                   rectBottomY-rectTopY);

        for (int n=1; n<=500; n++)
        {
            g.setColor(Color.white);
            g.fillOval (x, y, diameter, diameter);
            if (x + xChange <= rectLeftX)     xChange = -xChange;
            if (x + xChange >= rectRightX-8)  xChange = -xChange;
            if (y + yChange <= rectTopY)      yChange = -yChange;
            if (y + yChange >= rectBottomY-7) yChange = -yChange;
            x = x + xChange;
            y = y + yChange;
            g.setColor(Color.red);
            g.fillOval (x, y, diameter, diameter);

            try
            {
                sleep(50);
            }
            catch (InterruptedException e)
            {
                System.err.println("Sleep interrupted!");
            }
        }
    }
}
