Search code examples
javatimerdelayactionlistener

Stopping Timer after it have runned one time


In the game that I am making I have a Timer that I have set to 10_000 (that's every 10 seconds, right?).

I use this Timer to make an power up in the game only last for 10 seconds, the problem is that the Timer doesn't stop after the first time it have runned so the first time the player get that power up it will work fine but if the player get the same power up twice it won't have it for 10 second but depending on the Timer the player will get it a random time as long as it isn't over 10 seconds.

What I need to do is making the Timer stop right after it runs the first time so that it will start over again the next time the player get that power up.

How would I do this?


Solution

  • By default Swing Timers automatically cycle. To run the timer once only, you can use:

    timer.setRepeats(false);
    

    before calling timer.start().