我编写了一个 TimerTask 来在 JLabel 中显示当前日期和时间。以下是 TimerTask 代码,在正常情况下运行良好。当我在 GUI 运行时更改系统日期和时间时,计时器停止运行。当我更改系统日期和时间并且计时器停止运行时也不异常(exception)。 谁能告诉我发生了什么事?
private void startTimer()
{
// Start the clock
timer = new Timer();
timer.schedule(new TimeTask(), 0, 1000);
}
class TimeTask extends TimerTask
{
public void run()
{
try {
clockLabel.setText(new SimpleDateFormat("EEE , dd MMM , HH:mm:ss").format(Calendar.getInstance().getTime()));
System.out.println(clockLabel.getText());
} catch(Exception ex) {
ex.printStackTrace();
System.out.println("Exception : " + ex.getMessage());
}
}
}
最佳答案
不要将 TimerTask 与 Swing 一起使用,因为您很容易遇到并发问题,因为 TimerTask 将从 EDT 调用代码。而是使用 Swing Timer;这正是它的构建目的——在 Swing 事件线程上定期调用代码。
即,
private void startTimer() {
timer = new Timer(TIMER_DELAY, new TimerListener());
timer.start();
}
private class TimerListener implements ActionListener {
private final String PATTERN = "EEE , dd MMM , HH:mm:ss";
private final DateFormat S_DATE_FORMAT = new SimpleDateFormat(PATTERN);
@Override
public void actionPerformed(ActionEvent e) {
Date date = Calendar.getInstance().getTime();
String dateString = S_DATE_FORMAT.format(date);
clockLabel.setText(dateString);
}
}
关于java - 当系统日期更改时,获取系统日期和时间的 TimerTask 停止运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10111476/