How do I set Swing Timer initial delay?

The Swing javax.swing.Timer object fires the action event after the delay time specified in the constructor passed. For some reasons you might want the Timer class fires immediately after it was started.

To achieve this you can set the timer initial delay by calling the setInitialDelay(int initialDelay) method. The example below give you an example how to do it.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TimerInitialDelayDemo extends JFrame {
    private JLabel counterLabel = new JLabel();

     private Timer timer = null;
    
    public TimerInitialDelayDemo() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 200);

        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.CENTER));
        container.add(counterLabel);

        timer = new Timer(1000, new MyActionListener());

        //
        // Set initial delay of the Timer object. Setting inital delay
        // to zero causes the timer fires the event immediately after
        // it is started.
        //
        timer.setInitialDelay(0);
        timer.start();                
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TimerInitialDelayDemo().setVisible(true);
            }
        });
    }

    class MyActionListener implements ActionListener {
        private int counter = 10;

        public void actionPerformed(ActionEvent e) {
            counter = counter - 1;
            String text = "" + String.valueOf(counter) + "";
            counterLabel.setText(text);

            if (counter == 0) {
                timer.stop();
            }
        }
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply