Cositas.java



// EJEMPLO DE UN HILO -ANIMACION-
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;


class Cositas extends JFrame
{
	Dibujo JP = null;
	Frame Ventana_2 = null;

	public static void main(String R[]) { new Cositas(); }


	public Cositas()
	{
		this.setBounds(100, 100, 800, 300);
		this.setVisible(true);
	
		JP = new Dibujo();
		this.add(JP);
		JP.setBounds(0,0,800, 300);
		JP.setVisible(true);
	}

	protected void processWindowEvent(WindowEvent e)
        { if (e.getID() == WindowEvent.WINDOW_CLOSING) System.exit(0); }
}


class Dibujo extends JPanel implements Runnable
{
	Thread Hilo = new Thread(this);
        int x = 10;


	public Dibujo()
	{
		Hilo.start();
	}

	// 3.-  Se implementa el cuerpo del mEtodo start de la interfaz Runnable
        public void start( )
        {
                if (Hilo == null)
                {
                        Hilo.start();
                }
        }


	// 4.-  Se implementa el cuerpo del mEtodo run de la interfaz Runnable
        public void run( )
        {
                // AQUI VA LA ANIMACION
                while(x < 300)
                {
                        // 5.-  Se pone la pareja try-catch para interceptar una posible excepciOn.
                        try { Thread.sleep(500); }
                        catch(InterruptedException r)
                        {// CODIGO PARA LA ATENCION A LA INTERRUPCION
                        }
                        x += 10;
                        repaint();
                }
        }

        public void paint(Graphics G)
        {
                G.clearRect(0, 0, 400, 250);
                G.drawString("RAFA", x, 10);            // (cadena, x, y)
        }
}