Вы должны обновлять текст в отдельной теме каждую секунду.
В идеале вы должны обновлять компонент Swing только в EDT (потоке диспетчера событий), но после того, как я попробовал его на своей машине, использование Timer.scheduleAtFixRate дало мне лучшие результаты:
java.util.Timer http://img175.imageshack.us/img175/8876/capturadepantalla201006o.png
Версия javax.swing.Timer всегда отставала примерно на полсекунды:
javax.swing.Timer http://img241.imageshack.us/img241/2599/capturadepantalla201006.png
Я действительно не знаю почему.
Вот полный источник:
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 );
}
}
Вот модифицированный источник с использованием javax.swing.Timer
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();
}
Возможно, мне следует изменить способ вычисления строки с датой, но я не думаю, что здесь проблема
Я прочитал, что, начиная с Java 5, рекомендуется: ScheduledExecutorService Я оставляю вам задачу по ее реализации.