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

public class esercizioThread extends JPanel implements Runnable
{
	static Palla[] palline;
	Thread thread = null;
	
	public esercizioThread()
	{
		palline = new Palla[2];
		
		for (int k = 0; k < palline.length; k++)
			palline[k] = new Palla(this);
		thread = new Thread(this);
		thread.start();
	}
	public void paint(Graphics g)
	{
		super.paintComponent(g);
		for (int k = 0; k < palline.length; k++)
			palline[k].mostra(g);
	}
	public static void main(String[] a) 
	{ 
		JFrame f = new JFrame(); 
		f.setSize(400,400); 
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
		f.add(new esercizioThread()); 
		f.setVisible(true);
	}
	public void run()
	{
		while(thread != null)
		{
			for (int k = 0; k < palline.length; k++)
				palline[k].muovi(getWidth(), getHeight());
			repaint();
			try {
				thread.sleep(5);
			} catch(Exception e) {}
		}
	}
}

class Palla
{
	esercizioThread padre;
	float x, y, dim;
	Color color;
	float step = 1;
	float VX = 1, VY = 1;
	public Palla(esercizioThread p)
	{
		padre = p;
		this.x = (float)Math.random()*100;
		this.y = (float)Math.random()*100;
		this.dim = (float)Math.random()*20;
		this.color = new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255));
		this.step = 0.001f + (float)Math.random();
	}
	public void muovi(int w, int h)
	{
		x = x + step*VX;
		y = y + step*VY;
		if (x > w || x < 0) VX = VX*(-1);
		if (y > h || y < 0) VY = VY*(-1);
	}
	public void mostra(Graphics g)
	{
		g.setColor(color);
		g.fillOval((int)(x-dim/2), (int)(y-dim/2), (int)dim, (int)dim);
		g.setColor(Color.black);
		g.drawOval((int)(x-dim/2), (int)(y-dim/2), (int)dim, (int)dim);
	}
	public void moveTo(float x, float y)
	{
		this.x = x;
		this.y = y;
	}
}