Using a timer to count

Trying to write a timer to count down (e.g. rocket launch: 3-2-1-Go). It seems that I just completed once. I need to do this many times (almost recursively) until the value reaches 0.

As you will see, I have various println instructions to keep track of this. Here is my conclusion:

in the coundown constructor

in actionlistener

count

3

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

2

1

Go

which tells me that this timer does not actually count. It seems to wait one second and then complete the job.

How can I make this call myself until the timer reaches zero? Thanks!

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(); } 
+4
source share
2 answers

Remove myTimer.stop() from the end of actionPerformed . This is what prevents him from triggering subsequent events. The only place you want to call stop is inside if (countSeconds == 0) .

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

+6
source

Firstly, you stop the timer on the first pass:

 myTimer.stop(); <---- remove this call myTest.hideTestButtons(false); 

so that your timer is never called again.

By correcting this, you initialize

 int countSeconds = 3; 

every time in actionPerformed, so the counter will never end.

You need to transfer this to the class level and initialize it just before the timer starts.

+5
source

All Articles