How can I pause/sleep/wait in a java swing app?

Using Thread#sleep method in swing applications in main thread will cause the GUI to freeze (since the thread sleeps, events cannot take place). Thread#sleep method in swing applications is only allowed to be used only by SwingWorkers, and this in their #doInBackround method.

In order to wait in a swing application (or do something periodically), you will have to use a Swing Timer. Take a look at an example i have made:

import java.awt.FlowLayout;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer; //Note the import

public class TimerExample extends JFrame {
    private static final int TIMER_DELAY = 1000;
    private Timer timer;

    public TimerExample () {
        super();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(200, 200);
        setLocationRelativeTo(null);
        getContentPane().setLayout(new FlowLayout());

        timer = new Timer(TIMER_DELAY, e -> {
            System.out.println("Current Time is: " + new Date(System.currentTimeMillis()));
        });
        //timer.setRepeats(false); //Do it once, or repeat it?
        JButton button = new JButton("Start");
        button.addActionListener(e -> timer.start());
        getContentPane().add(button);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TimerExample().setVisible(true));
    }
}

Output after “Start” button is pressed:

Current Time is: Mon Feb 25 13:30:44 EET 2019

Current Time is: Mon Feb 25 13:30:45 EET 2019

Current Time is: Mon Feb 25 13:30:46 EET 2019

As you can see, Timer’s action listener fires every second.

So in your case:

timer = new Timer(TIMER_DELAY, e -> {
    if (currentIndexLabel != paint.length-1) {
        upateLabels();
        timer.restart(); //Do this check again after 1000ms
    }
});
button.addActionListener(e -> timer.start());

Leave a Comment