Leon
Leon

Reputation: 465

Stopping Java timer

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

Upvotes: 1

Views: 314

Answers (2)

bakriawad
bakriawad

Reputation: 345

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..

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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();
    }
}

Upvotes: 4

Related Questions