esercizio 2
Questo esercizio crea oggetti Cerchio in thread separati e li anima nella finestra dell'applet. La classe CerchioThreaded rappresenta l'oggetto il cui movimento é autonomo cioé non comandato dall'applet stessa. Sono stati presi gli accorgimenti standard per evitare lo sfarfallio, disegnando in una graphics offscreen gli oggetti cerchio e cancellando sempre e solo la versione offscreen. Tale tecnica impedisce di notare le fasi di disegno e cancellazione che possono sovrapporsi prima dell'avvenuta visualizzazione.
Tramite il parametro num é possibile indicare il numero di cerchi da disegnare.

package corsoDrZito.lez3.es2;

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

public class esercizio2 extends Applet implements Runnable
{
	public void init()
	{
		int num = 10;
		d = getSize();

		String param = getParameter("num");
		if (param!=null) num = Integer.parseInt(param);

		cerchi = new CerchioThreaded[num];
		for(int i=0;i<cerchi.length;i++)
		{
			cerchi[i] = new CerchioThreaded(d);
			cerchi[i].start();
		}

		im = createImage(d.width, d.height);
		myg = im.getGraphics();

		setBackground(new Color(48,64,96));

		t = new Thread(this);
		t.start();
	}

	public synchronized void update(Graphics g) { paint(g); }
	public synchronized void paint(Graphics g)
	{
		myg.clearRect(0, 0, d.width, d.height);

		for(int i=0;i<cerchi.length;i++)
			cerchi[i].paint(myg);

		g.drawImage(im, 0, 0, this);
	}

	public void run()
	{
		Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
		do
		{
			repaint();
			try
			{
				Thread.currentThread();
				Thread.sleep(10L);
			}
			catch(InterruptedException ex) {}
		}
		while(true);

	}

	private CerchioThreaded[] cerchi;

	private Image im;
	private Graphics myg;
	private Dimension d;
	private Thread t;
}

package corsoDrZito.lez3.es2;

import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Rectangle;

public class CerchioThreaded extends Thread
{
	public CerchioThreaded(Dimension d)
	{
		super();
		r = (int)(Math.random() * Math.min(d.width, d.height) / 6.) + 5;
		x = (int)(Math.random() * (d.width - r));
		y = (int)(Math.random() * (d.height -r));
		x_increment = (int)(Math.random()*8.) - 4;
		y_increment = (int)(Math.random()*8.) - 4;
		bounds = d;
	}

	public void run()
	{
		Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
		do
		{
			if(x + r >= bounds.width) x_increment = -Math.abs(x_increment);
			if(x < 0) x_increment = Math.abs(x_increment);
			if(y + r >>= bounds.height) y_increment = -Math.abs(y_increment);
			if(y < 0) y_increment = Math.abs(y_increment);
			x += x_increment;
			y += y_increment;
			try
			{
				Thread.currentThread();
				Thread.sleep(10L);
			}
			catch(InterruptedException ex) {}
		}
		while(true);
	}

	public synchronized void paint(Graphics g)
	{
		g.fillOval(x, y, r, r);
	}

	private int x, y, r;
	private int x_increment;
	private int y_increment;
	private Dimension bounds;
}