I’ve written a TimerTask to display current date and time in a JLabel. Following is the TimerTask code and that works well in normal scenario. When I change the system date and time when the GUI is running, the timer stops running. There was no exception when I changed system date and time and the Timer just stops running.
Can anyone tell me what is happening?
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());
}
}
}
Don’t use TimerTask with Swing as you can easily run into concurrency issues as TimerTask will be calling code off of the EDT. Instead use a Swing Timer; this is specifically what it is built for — calling code periodically on the Swing event thread.
i.e.,