Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Timer to Count Down

Tags:

java

timer

swing

Trying to write a timer to do a count down (like a rocket launch: 3-2-1-Go). What I have seems only to execute once. I need it to repeatedly (almost recursively) execute until the value reaches 0.

As you will see, I have various println statements to follow the progress of this. Here is my output:

in Coundown constructor

in ActionListener

counting down

3

What is wrong is that I am missing the following outputs:

2

1

Go

which indicates to me that this timer is not actually counting down. It seems to be waiting for one second and then terminating.

How can I get this to call itself until the timer reaches zero? Thank you!

public class StopWatch {

    JFrameMath myTest;
    int seconds;

    /* Constructor */
    public StopWatch(JFrameMath thisTest, int sec) {
        myTest = thisTest;
        seconds = sec;

        myTest.hideTestButtons(true);
        Countdown display = new Countdown(myTest);
    }
}

class Countdown extends JFrame implements ActionListener {

    private Timer myTimer = new Timer(250, this);
    JFrameMath myTest;

    public Countdown(JFrameMath thisTest) {

        System.out.println("in Coundown constructor");  

        myTimer.setInitialDelay(1150);
        myTest = thisTest;
        myTimer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        System.out.println("in ActionListener");      
        int countSeconds = 3;

        if(countSeconds == 0) {
            myTest.showTimeRemaining("Go");
            myTimer.stop();
            System.out.println("done");
        } else {
            System.out.println("counting down");
            myTest.showTimeRemaining(""+countSeconds);
            countSeconds--;
        }

        myTimer.stop();
        myTest.hideTestButtons(false);
    }
}

public void showTimeRemaining(JFrameMath thisTest, String numSec) {
  System.out.println(numSec);
    lblCountdown.setText(numSec);
    thisTest.pack();
}
like image 758
AndroidDev Avatar asked Dec 20 '22 17:12

AndroidDev


1 Answers

Remove myTimer.stop() from the end of actionPerformed. That is what's preventing it from triggering subsequent events. The only place where you want to call stop is inside if (countSeconds == 0).

Also, I don't know if it's a typo or a test, but you need to remove the line int countSeconds = 3; from actionPerformed.

like image 198
João Silva Avatar answered Dec 24 '22 03:12

João Silva