package ejemplo;

import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Color;

/**
 * Ejemplo 1.5-1 Hola mundo.
 *   Copyright (C) Victor Lozano 2011 
 *   victor.lozano@mildecabeza.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see .
 *
 */
 
public class HolaMundo extends JApplet implements Runnable{    
    final int TIEMPO_ESPERA = 5;
    final int ANCHO = 300;
    final int ALTO = 200;
    final int ANCHO_TEXTO = 70;
    final int ALTO_TEXTO = 10;
    Thread hilo_principal = null;
    private int pos_x;
    private int pos_y;

    @Override
    public void init() {
        pos_x = 100;
        pos_y = 100;
        requestFocus();
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.black );
        g.fillRect(0, 0, ANCHO, ALTO);
        g.setColor(Color.white );
        g.drawString("¡Hola Mundo!", pos_x, pos_y);
    }   

    @Override
    public void start() {
        hilo_principal = new Thread(this);
        hilo_principal.start();
    }

    @Override
    public synchronized void stop() {
        hilo_principal = null;
    }

    public void run() {
        boolean rebota_x = false;
        boolean rebota_y = false;
        while (true) {            
            if((pos_x > ANCHO - ANCHO_TEXTO)||(pos_x < 0))
                rebota_x = !rebota_x;
            
            if((pos_y > ALTO)||(pos_y < ALTO_TEXTO))
                rebota_y = !rebota_y;

            if(rebota_x){
                pos_x--;
            }else pos_x++;            

            if(rebota_y){
                pos_y--;
            }else pos_y++;
            
            repaint();

            try {
                Thread.sleep(TIEMPO_ESPERA);
            } catch (InterruptedException e){}
        }
    }
}

