Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: mytextarea.setText("hello") + Thread.sleep(1000) = strange result

I have something like this:

for(int i=0; i<5; i++){
    mytextarea.setText("hello " + i);
    try{
        Thread.currentThread().sleep(1000); //to give time for users to read
    } catch(Exception e){}
}

I'm expecting it will display "hello 0" in the text area, wait for 1 second, then display "hello 1", then wait for 1 second, etc.

But what happen is different, it waits for 5 seconds, then it displays "hello 4".

Any idea?

like image 810
evilReiko Avatar asked Dec 31 '25 07:12

evilReiko


2 Answers

Yes - you're basically blocking the UI thread, so it's never getting round to actually updating.

Sleeping in a UI thread is a really bad idea.

If you want to do something like this, you should use a Timer. (I'm assuming you're using Swing. If not, please edit your question to indicate which UI framework you're using.)

You should also note that Thread.sleep is a static method. You're using it as if it were an instance method. Admittedly you happen to be calling it "on" the current thread, but your usage suggest that you think that:

Thread t = new Thread(...);
t.start();
t.sleep(1000);

would make the new thread sleep. It wouldn't - it would make the current thread sleep, because that's what Thread.sleep always does. IMO it was a mistake for Java to allow you to call static methods in this way - if you're using Eclipse, there's an option to make this a warning or error.

like image 85
Jon Skeet Avatar answered Jan 01 '26 21:01

Jon Skeet


Like explained in Jon Skeet's answer, you should use a timer since you can't block the EDT and expect UI updates. Below is your sample snippet rewritten to use a Swing timer.

ActionListener action = new ActionListener() {
    int i = 0;

    public void actionPerfomed(ActionEvent e) {
        mytextarea.setText("hello " + i++);
    }
};
new javax.swing.Timer(1000, action).start();

See How to Use Swing Timers in the Swing Tutorial for more information about timer capabilities.

like image 30
Samuel Sjöberg Avatar answered Jan 01 '26 20:01

Samuel Sjöberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!