Quisiera poner un reloj (supongo que algo asI como un label dinAmico que se va actualizando) en una interfaz que vengo haciendo y no se cOmo hacerlo. Leí algunos ejemplos de hacer un reloj por ahi, pero me resultan muy complicados, sólo quisiera algo lo mAs simple posible que me muestre la hora, si es posible cada dato(hora, min, sec) en un label aparte y si tambiEn se pudiera hacer por consola mejor aun para entenderlo, esq no se mucho de esto, aun soy estudiante :-( si alguien me pudiera ayudar le estaría muy agradecido.
Saludos.
Bueno, tengo este ejemplo de hace un tiempo, espero te sirva:
Clase Principal:
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Reloj extends JFrame
{
private static final long serialVersionUID = 1L;
JLabel reloj, hora;
Reloj()
{
setTitle("Reloj");
setLayout( new FlowLayout() );
reloj = new JLabel("Reloj:");
ThreadClock clock = new ThreadClock();//Creación de objeto tipo ThreadClock
add( reloj );
add( clock );//Se agrega el panel de la clase ThreadClock
Thread hilo = new Thread( clock );//Se crea un hilo
hilo.start();//Se inicia el hilo
pack();
setVisible( true );
setDefaultCloseOperation( EXIT_ON_CLOSE );
}
public static void main( String args[] )
{
new Reloj();
}
}
Clase ThreadClock:
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ThreadClock extends JPanel implements Runnable
{
private static final long serialVersionUID = 1L;
JLabel labelhour;
int hora, minuto, segundo;
public ThreadClock()
{
labelhour = new JLabel("");
add( labelhour );//Se añade el label al panel
}
public void run()//Inicio del hilo
{
while( true )
{
Calendar calendar = Calendar.getInstance();
Date hora = calendar.getTime();//Obtebemos los datos, hora, fecha
DateFormat dateformat = DateFormat.getTimeInstance();//Obtenemos la hora
String horaActual = dateformat.format(hora);//formateamos para que nos retorne la hora
labelhour.setText( horaActual );//Añadimos la hora al label
try
{
Thread.sleep(1000);//Dormimos el hilo momentaneamente para que no se bloquee el programa
}
catch ( InterruptedException er )
{
er.printStackTrace();
}
}
}
}
Eso es todo, espero te sirva.