ANIMACION_1.java



// EJEMPLO DE ANIMACION CON UN HILO Y SU CONTROL (ok)
// AHORA SI YA TIENE EL CONTROL
// x = getBounds().width

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


public class ANIMACION_1 extends JFrame
{
	NuevoHilo Movil = new NuevoHilo( "<>", Color.red );
	JButton B_I_P = new JButton("INICIAR");
	boolean OK = false;			// Inicialmente la animaciOn estA detenida

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

	public ANIMACION_1()
	{
		this.getContentPane().setLayout(null);		// Contenedor nulo
		this.setTitle("ANIMACION 1.0");		// Titulo de la ventana
		this.setResizable(false);			// No es redimensionable
		this.setLocation(100, 100);			// Posicion desde la esquina superior izquierda del monitor
		this.setSize(new Dimension(800, 500));		// Dimensiones

		add(Movil); Movil.setBounds(30, 30, 600, 300);
		// Se inserta el botOn, se le pone color del fondo y color del frente (texto)
		add(B_I_P); B_I_P.setBackground(Color.blue); B_I_P.setForeground(Color.yellow);
		B_I_P.setBounds(60, 360, 90, 30);		// Se posiciona
		B_I_P.addActionListener(new Botonazo());	// Se captura el evento del ratOn sobre el botOn

		setVisible(true);				// 2.-	Se muestra la ventana
	}

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

	class Botonazo implements ActionListener
	{
		public void actionPerformed(ActionEvent EVENTO)
		{
			if ( OK ) { B_I_P.setText("MOVER"); Movil.parar(); OK = false; }
			else { B_I_P.setText("PARAR"); Movil.mover(); OK = true; }
		}
	}

}

class NuevoHilo extends JPanel implements Runnable 
{
	int x = 40, y = 50, N = 0;
	String Figura;
	boolean ciclo = true;
	Color ColorFondo = null;

	Thread hilo = null;

	public NuevoHilo ( String Figura, Color ColorFondo )
	{
		hilo = new Thread(this);
		this.ColorFondo = ColorFondo;
		this.Figura = Figura;
		hilo.start();
		hilo.suspend();
	}

	public void run()
	{
		while ( ciclo )
		{
			if (N < 100) { x += 5; N += 1; }
			else ciclo = false;
			repaint();
			try { hilo.sleep(50); } catch (InterruptedException e) {}
		}
	}

	public void paint(Graphics g)  
	{
		g.setColor(ColorFondo); g.fillRect(0, 0, 600, 300);
		g.setColor(Color.white); g.drawString(Figura, x, 50);
	}

	void mover() { hilo.resume(); }
	void parar() { hilo.suspend(); }
}