Search code examples
javaswingactionlistenerjavax.swing.timer

Make a Swing Timer execute N times?


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

Solution

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