1
new Timer(1000, new ActionListener() {
 @Override
 public void actionPerformed(ActionEvent e) {
 timeout--;
 if(timeout>=1){
 status1.setText("Time out: " + timeout);
 }else{
 patient1.setText("Patient: ");
 status1.setText("Status: Available");
 doctor.get(0).setStatus(true);
 countDoc++;
 setDoc.setText(avDoc + countDoc);
 timeout = 24;
 }
 }
}).start();

How to stop this piece of timer at the end of the else statement? I really scratched my head for this and searched almost everywhere

Hovercraft Full Of Eels
286k25 gold badges268 silver badges391 bronze badges
asked Nov 26, 2014 at 16:50

2 Answers 2

4

If you're trying to stop the Timer from within its ActionListener, then you can get the reference to the Timer object from the ActionEvent's getSource() method, and then stop it by calling stop() on the reference:

((timer) e.getSource()).stop();

or to break it down:

// assuming an ActionEvent variable named e
Timer timer = (Timer) e.getSource();
timer.stop();

and in context:

public void actionPerformed(ActionEvent e) {
 timeout--;
 if(timeout>=1){
 status1.setText("Time out: " + timeout);
 }else{
 patient1.setText("Patient: ");
 status1.setText("Status: Available");
 doctor.get(0).setStatus(true);
 countDoc++;
 setDoc.setText(avDoc + countDoc);
 timeout = 24;
 ((timer) e.getSource()).stop();
 }
}
answered Nov 26, 2014 at 16:51
Sign up to request clarification or add additional context in comments.

3 Comments

I got it working now but another question. Timer timer = (Timer) e.getSource(); What does the Timer in bracket does?
@user3083413: I'm glad that you've got it working. What do you mean by "bracket"? Do you mean the (Timer) statement? That's a cast which is required since getSource() is declared to return Object.
Understood fully now. Thanks sir
0

define the timer first as in:

Timer tim = new Timer(......)
tim.start();
tim.stop();

this will allow you yo stop the timer anywhere (providing you make it global)

you can also change it's attributes easily if you tie it to a var rather than creating an object like that..

answered Nov 26, 2014 at 16:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.