Trafico.java_



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

public class Trafico extends JPanel implements KeyListener
{
	boolean Corriendo = false;	// EstA corriendo el hilo?
	Anima_Num NUMERO[] = new Anima_Num[4];
	int x_a, x_n, y;		// x_anterior, x_nueva, y
	String NUM = "";
	
	public Trafico()
	{
        	addKeyListener(this);
		Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
	}

	public synchronized void paint(Graphics G)
	{
		if (!Corriendo)
		{
			G.setColor(Color.black);  G.fillRect(0, 0, 570, 310);
			G.setColor(Color.yellow); PintaManzanas(G);
		}
		else
		{
			G.setColor(Color.black);  G.drawString(NUM, x_a, y);
			G.setColor(Color.yellow); G.drawString(NUM, x_n, y);
		}
	}
	
	public void update(Graphics G) { paint(G); }
	
	void PintaManzanas(Graphics G)
	{
		int w = 40, h = 30;	// w = width, h= hight
		int x = 10, y = 10;

		for (int R = 0; R < 5; R++)
		{
			x = 10;
			for (int C = 0; C < 8; C++)
			{
				G.drawRect(x, y, w, h);
				x += 70;
			}
			y += 60;
		}
	}
	
	public void Imprime(int x_a, int x_n, int y, String NUM)
	{
		this.x_a = x_a;
		this.x_n = x_n;
		this.y   = y;
		this.NUM = NUM;
		repaint();
	}
	
	public void keyTyped(KeyEvent e)  {}	// No me interesa
	public void keyPressed(KeyEvent e){}	// No me interesa
	public void keyReleased(KeyEvent e)
	{
		System.out.println(e.getKeyText(e.getKeyCode()));
		String Tecla = e.getKeyText(e.getKeyCode());
		int Numeros = 0;
		if (Tecla.equals("F1") || Tecla.equals("F2") || Tecla.equals("F3") || Tecla.equals("F4"))
		{
			if (!Corriendo)
			{
				Corriendo = true;
				Numeros = e.getKeyCode() - 111;		// N nUmeros
				y = 60;
				for (int n = 0; n < Numeros; n++)
				{
					NUMERO[n] = new Anima_Num(y, n+1, this, (n + 1) * 200);
					new Thread(NUMERO[n]).start();
					y += 60;
				}
			}
		}
		else if (Tecla.equals("Introduzca")) { }
	}
}

class Anima_Num extends Thread
{
	int x_a, x_n, y, SLEEP;
	String NUM = "";
	Trafico TRAFICO;

	public Anima_Num(int y, int numero, Trafico TRAFICO, int SLEEP)
	{
		this.y = y;
		this.NUM = "" + numero;
		this.TRAFICO = TRAFICO;
		this.SLEEP = SLEEP;
	}

	public void run( )
	{
		while(true)
		{
			try { Thread.sleep(50); }
			catch(InterruptedException r){}
			x_n =  (x_n == 570) ? 0 : x_n+10;
			TRAFICO.Imprime(x_a, x_n, y, NUM);
			x_a = x_n;
		}
	}
}