Reputation: 195
I have a gui and I want to display some text and then wait a little.
My code looks something like this:
//do something (add JTextArea, revalidate, repaint)
try{
Thread.sleep(4000);
}
catch(InterruptedException e){
}
The "something" should be carried out and then the code should wait. However, I see "something" happening only after the waiting time is over. How can I achieve the desired behaviour?
Upvotes: 1
Views: 858
Reputation: 285405
Yeah, as I thought, you're calling sleep on the Swing event thread.
Solution: don't. Calling Thread.sleep(...)
on the event thread will prevent it from performing its necessary actions, including drawing your GUI (which is why you're not seeing the pre-sleep changes that you are expecting).
Use a Swing Timer or a background thread. The details of the solution will depend on your problem.
In your edit you state:
I have a gui and I want to display some text and then wait a little.
Then use a Swing Timer. You can find the tutorial here: How to use Swing Timers. In brief, you pass the time delay and an ActionListener into the Timer's constructor, you'll want to set it to no repeats, and then you call start on it. The ActionListener's code will be called after the delay occurs.
Upvotes: 3