import java.awt.*;
import java.awt.event.*;


public class Bounce {
    public static void main(String[] args) {
	Frame frame = new BounceFrame();
	frame.setVisible(true);
    }
}

class BounceFrame extends Frame {

    private Panel canvas;

    public BounceFrame() {
	putInCenter(); // put frame in center of screen
	addWindowListener(new WindowTerminator());

	setLayout(new BorderLayout()); 
	canvas = new Panel();
	add(canvas,"Center");


	Panel buttonPanel = new Panel();
	Button startButton = new Button("Start");

	startButton.addActionListener(new StartItUp());

	buttonPanel.add(startButton);

	Button closeButton = new Button("Close");
	closeButton.addActionListener(new CloseItUp());
	
	buttonPanel.add(closeButton);
	add(buttonPanel,"South");

    }

    private class WindowTerminator extends WindowAdapter {
	public void windowClosing(WindowEvent e) {
	    System.exit(0);	
	}
    }
    private class StartItUp implements ActionListener {
	public void actionPerformed(ActionEvent evt) {
	    Bouncer b = new Bouncer(canvas);
	    b.bounce();
	}
    }
    private class CloseItUp implements ActionListener {
	public void actionPerformed(ActionEvent evt) {
	    System.exit(0);
	}
    }
    /* put frame in center of screen.  screenSize is the screen size as
       a Dimension object.  Size is 1/2 of the entire screen.
       Taken from Core Java Vol. 1, p. 306
    */
    private void putInCenter() {
	Toolkit kit = Toolkit.getDefaultToolkit();
	Dimension screenSize = kit.getScreenSize();
	int screenWidth = screenSize.width;
	int screenHeight=screenSize.height;
	setSize(screenWidth/2, screenHeight/2);
	setLocation(screenWidth/4,screenHeight/4);
    }	
}

class Bouncer {

    private Panel box;
    private static final int XSIZE=10;
    private static final int YSIZE=10;
    private int x=0;
    private int y=0;
    private int dx=2;
    private int dy=2;

    public Bouncer(Panel b) {
	box=b;
    }

    public void draw() {
	Graphics g = box.getGraphics();
	g.fillOval(x,y,XSIZE,YSIZE);
	g.dispose();
    }

    public void move() {
	Graphics g = box.getGraphics();
	g.setXORMode(box.getBackground());
	g.fillOval(x,y,XSIZE,YSIZE);
	x+=dx;
	y+=dy;
	Dimension d = box.getSize();
	if (x<0) {
	    x=0;
	    dx=-dx;
	}
	if (x+XSIZE >= d.width) {
	    x=d.width-XSIZE;
	    dx=-dx;
	}
	if (y<0) {
	    y=0;
	    dy=-dy;
	}
	if (y+YSIZE >= d.height) {
	    y=d.height-YSIZE;
	    dy=-dy;
	}
	g.fillOval(x,y,XSIZE,YSIZE);
	g.dispose();
    }

    public void bounce() {
	draw();
	for (int i=1; i<=1000; i++) {
	    move();
	    try {
		Thread.sleep(5);
	    }
	    catch(InterruptedException e){
	    }
	}
    }
}

