import java.awt.*;
import javax.swing.*;
import java.lang.*;

public class Ball extends JComponent {
    int radius;
    int x = 100;
    int y = 100;
    int xdir = 1;
    int ydir = 1;
	
    public void paint(Graphics g) {
		g.fillOval(x-radius,y-radius,2*radius,2*radius);
    }    
	
    public Dimension getPreferredSize() {
		return new Dimension(500, 300);
    }
	
    public Ball(int r) {
		radius = r;
		Thread t = new Updater();
		t.start();
    }
	
    private class Updater extends Thread {
		public void run() {
			while(true) {
				Dimension d = getSize();
				
				if (x <= radius)
					xdir = 1;
				else if (x >= d.width-radius)
					xdir = -1;
				
				if (y <= radius)
					ydir = 1;
				else if (y >= d.height-radius)
					ydir = -1;
				
				x += 2 * xdir;
				y += 2 * ydir;
				repaint();
				
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {}
			}
		}
    }
}

