2

How can I adjust this Timer code so that it executes four times and then stops?

timer = new Timer(1250, new java.awt.event.ActionListener() {
    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
         System.out.println("Say hello");
    }
});
timer.start();
mKorbel
  • 109,525
  • 20
  • 134
  • 319
JaLe29
  • 57
  • 1
  • 9

2 Answers2

3

You could do:

Timer timercasovac = new Timer(1250, new ActionListener() {
    private int counter;

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Say hello");
        counter++;
        if (counter == 4) {
            ((Timer)e.getSource()).stop();
        }
    }
});
timercasovac.start();
Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

You need to count yourself and then stop the Timer manually:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class TestTimer {

    private int count = 0;
    private Timer timer;
    private JLabel label;

    private void initUI() {
        JFrame frame = new JFrame("test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label = new JLabel(String.valueOf(count));
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
        timer = new Timer(1250, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (count < 4) {
                    count++;
                    label.setText(String.valueOf(count));
                } else {
                    timer.stop();
                }
            }
        });
        timer.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestTimer().initUI();
            }
        });
    }

}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117