John Arckai
John Arckai

Reputation: 93

Stoping a Swing Timer within the actionPerformed Method?

How would I stop a Swing timer within it's actionPerformed method? I am able to start and stop the timer outside the actionPerformed method but not with in the method how would I accomplish this?

final int i =0;
    final Timer timer = new Timer(10, new ActionListener() {
        int i = 0;
        public void actionPerformed(ActionEvent evt) {
            i++;
            System.out.println(i);
            if(i == 100) {
                timer.stop();
            }


        }    
    });
    timer.start();

Upvotes: 0

Views: 421

Answers (3)

camickr
camickr

Reputation: 324207

You can get the Timer from the ActionEvent:

Timer timer = (Timer)evt.getSource();

Upvotes: 1

Paul Samsotha
Paul Samsotha

Reputation: 209132

Declare the timer as a class member. Also you probably want to declare int i as a class member also, since creating a new one inside the timer makes no sense, if you're trying to increment it each repeat. See my code corrections

Timer timer = null;
int i = 0;
public Constructor() {

    timer = new Timer(10, new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            i++;
            System.out.println(i);
            if(i == 100) {
                timer.stop();
            }
        }    
    });
    timer.start();
}

Upvotes: 2

Howard
Howard

Reputation: 39217

Stopping swing timers from within the action method works fine. I think the issue with your code is, that it doesn't even compile because you are accessing the timer variable before it is assigned.

Split the assignment into two parts like below and it'll compile and work fine.

final Timer timer = new Timer(10, null);
timer.addActionListener(new ActionListener() {
    ...
});

Upvotes: 3

Related Questions