Usted tiene que actualizar el texto en un hilo separado cada segundo.
Idealmente debería actualizar los componentes de impulsión solo en el EDT (evento hilo despachador), pero, después de lo probé en mi máquina, usando Timer.scheduleAtFixRate me dio mejores resultados:
java.util.Timer http://img175.imageshack.us/img175/8876/capturadepantalla201006o.png
El javax.swing. versión temporizador fue siempre alrededor de la mitad segundo por detrás:
javax.swing.Timer http://img241.imageshack.us/img241/2599/capturadepantalla201006.png
realmente no sé por qué.
Aquí está el código fuente completo:
package clock;
import javax.swing.*;
import java.util.*;
import java.text.SimpleDateFormat;
class Clock {
private final JLabel time = new JLabel();
private final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
private int currentSecond;
private Calendar calendar;
public static void main(String [] args) {
JFrame frame = new JFrame();
Clock clock = new Clock();
frame.add(clock.time);
frame.pack();
frame.setVisible(true);
clock.start();
}
private void reset(){
calendar = Calendar.getInstance();
currentSecond = calendar.get(Calendar.SECOND);
}
public void start(){
reset();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
public void run(){
if(currentSecond == 60) {
reset();
}
time.setText(String.format("%s:%02d", sdf.format(calendar.getTime()), currentSecond));
currentSecond++;
}
}, 0, 1000);
}
}
Aquí está la fuente modificado usando javax.swing.Temporizador
public void start(){
reset();
Timer timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(currentSecond == 60) {
reset();
}
time.setText(String.format("%s:%02d", sdf.format(calendar.getTime()), currentSecond));
currentSecond++;
}
});
timer.start();
}
Probablemente debería cambiar la forma en que se calcula la cadena con la fecha, pero no creo que ese es el problema aquí
He leído, que, desde Java 5 del recomendado es: ScheduledExecutorService Te dejo la tarea de implementarlo.
no hago swing ampliamente, por lo que hay una respuesta detallada de la mía, pero Google parece dar suficientes pistas: http: // www .google.com/search? q = java + swing + clock Hasta el punto: necesita actualizar el reloj * usted mismo * cada vez en un hilo de fondo. – BalusC
@BalusC pero lo hace google extensamente;) – Bozho