'How to reset a countdown timer when the same button is pressed
So I'm making this game which gives the player 30 seconds to choose an answer. If they choose an option, the timer resets back to the 30 seconds.
@Override
public void actionPerformed(ActionEvent e) {
//the idea is that when this button is clicked, the timer starts.
if(e.getSource() == button) {
//random gui stuff which i won't include
//calls the method for timer
runner();
}
This is my runner() method:
public void runner() {
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final Runnable runnable = new Runnable() {
int countdownStarter = 30;
public void run() {
//this is my JLabel that prints out the timer
label.setText("" + countdownStarter);
countdownStarter--;
if (countdownStarter < 0) {
label.setText("");
/*Random GUI stuff here I won't show*/
scheduler.shutdown();
}
}
My problem is, the timer does run when the button is clicked however it creates a new "timer" so on my GUI it just flickers between the two different times. For example if the already existing timer is at 5 seconds (left) and I click the button, the JLabel text flickers between 5/30, 4/29, 3/28, 2/27 .. ect but in reality I just want it to stop the existing timer.
Not sure what I can do and I could really appreciate any help since i'm very new to swing and gui stuff.
Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
