Caffeinated
Caffeinated

Reputation: 12484

I'm having trouble using the Swing Timer correctly(being able to call it multiple times)?

I was encouraged to use the Java Swing timer rather than the crude method of Thread.sleep(2000); - but this is giving me issues.

Specifically , I am not sure how to be able to call a function that will execute the timer. Say that my timer is 20 minutes, I want to be able to say something like:

for(int i = 0; i<10; i++){
   call20MinuteTimer();
}

Then that timer would run 10 times(i.e for 200 minutes it's looping). With Thread.sleep() the above wwas very easy. I could just say it.

Here's how my code looks right now :

    ActionListener a9 = new ActionListener(){
        public void actionPerformed(ActionEvent evt){

        DateFormat dateFormat = new SimpleDateFormat("HH:mm");
        String currentTime = (String) dateFormat.format(new Date());

        combo2.append("You completed " + i + ""
        +  " pomodoros! At " + currentTime + " \n");
         Toolkit.getDefaultToolkit().beep();
        }
      };



    Timer newTimer = new Timer(500, a9);
    newTimer.start();
    newTimer.setRepeats(false);

If I take all those above lines of code an put it into a function(outside of main), It will only call it once.

Maybe I am unclear on what's happening? I'm just lost on this. thanks

Upvotes: 1

Views: 46

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

To have a timer loop "x" times, give it a count field:

ActionListener a9 = new ActionListener(){
  private int count = 0;

  public void actionPerformed(ActionEvent evt){
    if (count < MAX_COUNT) { // MAX_COUNT is an int constant, here, 10

      // ... do something

    } else {
      // we're done -- stop the Timer
      ((Timer)evt.getSource()).stop();
    }
    count++;
  }
};

The key is that while it might seem that you're doing a loop type action but to do this you don't use a loop. You instead have to have this code called repeatedly by the Timer.

Also, this: Timer newTimer = new Timer(500, a9); makes it repeat every 500 milliseconds.

And this: newTimer.setRepeats(false); makes it not repeat at all! You will want to get rid of this line if you want your timer to repeat.

Upvotes: 3

Related Questions