How can I get the time left in a util.Timer? What I want to do is to add a progressbar that displays time left until the timer starts over.
This is what I've got this far:
int seconds = 8;
java.util.Timer timer = new Timer();
timer.schedule( new TimerTask(){
public void run(){
// Do something
// Add a progressbar that displays time left until the timer "starts over".
},0,(long) (seconds*1000));
You would need a second timer to refresh the gui in a specific interval.
Another way to achieve this, would be to activate a single timer every second and update the counting in the ui. If the time is up, call your specific action.
A simple expample with console output only:
It's output would be:
Then simply change the System.out's with your code to update the progress bar. Remember:
java.util.Timer
starts its ownThread
. Swing is not thread safe, so you need to put every gui changing code intoSwingUtilities.invokeLater()
!If you're not doing any long running tasks, every time your timer reachs the 8 seconds mark, you may want to use
javax.swing.Timer
directly. It uses the EDT and not its ownThread
, so you don't need to synchronize your calls to Swing components withSwingUtilities.invokeLater()
.Also see:
javax.swing.Timer vs java.util.Timer inside of a Swing application
All you need to do is declare a long variable
timeleft
in your MainActivity.Then, when you create a new Timer, set the "onTick" override to update the timeleft variable each "onTick" (which in the following example is 1000 milliseconds )
Your app can access then the variable timeleft every time you need to check how much time is left.