Buscar en este blog

domingo, 3 de junio de 2012

Java - Thread - Reloj


package thread;

import java.awt.BorderLayout;
import java.awt.Color;
import java.util.Calendar;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;


public class Reloj extends JPanel implements Runnable {

//atributos
private int horas=0;
private int minutos=0;
private int segundos=0;
private JLabel hora= new JLabel();

//contructor Reloj
public Reloj(){

//interfaz grafica
this.setLayout(new BorderLayout());
this.setBorder(new LineBorder(Color.black,2));
hora.setOpaque(true);
hora.setBackground(Color.white);
this.add(hora,BorderLayout.CENTER);

//leer hora sistema
Calendar c= Calendar.getInstance();
horas= c.get(Calendar.HOUR_OF_DAY);
minutos= c.get(Calendar.MINUTE);
segundos= c.get(Calendar.SECOND);

//Formatear hora
this.mostrarHora();

//Arrancar reloj
new Thread(this).start();
}
public void run(){
while(true){
//paramos un 1 seg
try{
Thread.sleep(1000);
}
catch(InterruptedException ex){
ex.printStackTrace();
}
//incrementar un 1 seg.
segundos++;

//calcular los valores
if(segundos==60)
{
segundos=0;
minutos++;
if(minutos==60)
{
minutos=0;
horas++;
if(horas==24)

horas=0;

}
}
this.mostrarHora();
}
}
private void mostrarHora(){
//formatear la hora
StringBuffer tmp= new StringBuffer();
if(horas<10)
tmp.append(0);
tmp.append(horas);
tmp.append(":");
if(minutos<10)
tmp.append(0);
tmp.append(minutos);
tmp.append(":");
if(segundos<10)
tmp.append(0);
tmp.append(segundos);

hora.setText(tmp.toString());
}
}

------------------------------------------------------------------------------------------------------------


ackage thread;

import java.awt.FlowLayout;

import javax.swing.JFrame;

public class RelojTest {
public static void main (String args[]){

JFrame frame= new JFrame("Reloj");
frame.setVisible(true);
frame.setBounds(10, 10, 250, 70);
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new Reloj());

}
}




No hay comentarios:

Publicar un comentario

Entradas Relacionadas