0

I have the following code to display current time in swing application.

private void startClock(StateBar stateBar)
{
    ActionListener listener = new ActionListener()
    {
          public void actionPerformed(ActionEvent event)
          {
            stateBar.setTime(Clock.currentDateStr());
          }
    };

    timer = new Timer(1000,listener);
    timer.start();
}

But it seems to execute listener code not at timer start but after one second from start. I mean when I open the panel with my clock the date appears with 1 second delay. Is it possible to fire execution on my code immediately at start of the timer?

user2374573
  • 59
  • 1
  • 3
  • 11

2 Answers2

3

public void setInitialDelay(int initialDelay) - Sets the Timer's initial delay, the time in milliseconds to wait after the timer is started before firing the first event. Upon construction, this is set to be the same as the between-event delay, but then its value is independent and remains unaffected by changes to the between-event delay.

Use 0

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
1

It is a different timer, but will still accomplish the same this.

Timer timer = new Timer();
timer.schedule(timerTask, 0, 1000);

This will schedule a task that will run every 1000ms, and will run the first time at 0ms.

Matt Clark
  • 27,671
  • 19
  • 68
  • 123