user2460978
user2460978

Reputation: 725

java: why waiting some time is making my program not execute sequentially?

I have a GUI that displays a certain iterating process step by step. I want it to make one step, display the step, wait 1s, and repeat, ...

The code:

while (! finished()) {
    advance(); // make and display one step
    try {
        Thread.sleep(1000);
    }
    catch (InterruptedException e) {       
    }
}

What happens, though, is that nothing is printed until the whole added time of all sleep calls pass, and then all the steps are printed at once. How can I make the execution flow sequentially?

Note: I tried replacing the sleep call with a very long, useless loop and the behaviour was the same.

Upvotes: 0

Views: 316

Answers (1)

nachokk
nachokk

Reputation: 14413

You have to do this task in a separate Thread. You are freezing your gui. You can use SwingWorker. Here you have a nice article Why do we need SwingWorker?

Note that swingWorker only will execute once. If you want to execute more time you have to take a look for javax.swing.Timer also

Note that the Swing timer's task is performed in the event dispatch thread. This means that the task can safely manipulate components, but it also means that the task should execute quickly. If the task might take a while to execute, then consider using a SwingWorker instead of or in addition to the timer.

Upvotes: 2

Related Questions