0

I am building a video game that uses a large number of timers that I would like to suspend if the user hits the Pause button. If the user then hits the Continue button I would like to either restart them, or if need be, potentially create new timers with what was remaining from the original one's.

Is there a way to get the amount of time remaining on a Java Timer before it would normally expire?

Thanks.

user1104028
  • 381
  • 7
  • 18

1 Answers1

1

You can't get the elapsed time from a java.util.Timer or javax.swing.Timer. To one of your points, javax.swing.Timer has a stop() method that can be used to suspend the timer and the start() method can be used to restart it.

If you aren't dependent on the thread interaction, there are other classes that have the functionality you requested.

The guava library has a Stopwatch class that does what you want.

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Stopwatch.html

Spring has one too:

http://docs.spring.io/spring/docs/2.0.x/api/org/springframework/util/StopWatch.html

John Scattergood
  • 1,032
  • 8
  • 15
  • So I guess with these I would have to start the StopWatch upon setting the timer, and when I want to "suspend" the timer, do some math to calculate remaining time till the timer would have gone off? Would this be accurate? – user1104028 Dec 19 '15 at 15:51
  • Are you relying on TimerTasks for something? It would be easier to combine simple threads with the stopwatch than trying to combine the two – John Scattergood Dec 19 '15 at 16:16
  • Yes, all of my game object movement is controlled by java.swingx.Timers which keeps events in sync with the Event Dispatch Queue. Wish Java Swing Timers supported this. Would like to avoid having to concoct something myself. – user1104028 Dec 19 '15 at 21:54
  • @user1104028 In your initial comments you mentioned that you wanted to suspend the timers before they expire, but I checked javax.swing.Timer and it has a stop method which suspends the timer. I assumed you were using java.util.Timer. To keep track of the elapsed time, why not subclass it and store the time when the Timer starts and stops and add an accessory for the elapsed time? – John Scattergood Dec 20 '15 at 07:03
  • That's a good idea! I'll try that. – user1104028 Dec 20 '15 at 18:45