Reputation: 23027
I want to paint a panel blue, then wait five seconds, then do other stuff.
Now I have the following piece of code, which I expect to do what I want. Here it is:
JPanel somePanel = getSomePanel();
somePanel.setBackground(Color.BLUE);
Object lock = new Object();
synchronized (lock) {
try {
lock.wait(5000);
}
catch (InterruptedException exc) { }
}
// Do other stuff
But instead, it waits five seconds and then paints the component blue.
Upvotes: 0
Views: 89
Reputation: 17794
The others are right, if you are waiting on the event dispatch thread, then this thread will not do any painting in the meantime.
There is a trick however, that should help you without starting a new thread: call paintImmediately after setting the background color.
somePanel.paintImmediately(0, 0, somePanel.getWidth(), somePanel.getHeight());
Upvotes: 3
Reputation: 285405
Don't do the synchronized code with locking on the Swing event thread as all you're doing is locking Swing itself and freezing the GUI. Google "Concurrency in Swing" for the details. Myself I'd use a Swing Timer for this. Note that your post uses the multithreading tag, but you don't actually do multithreading anywhere.
Upvotes: 4
Reputation: 24897
Do not wait in a GUI event handler - it prevents the processing of messages, eg. repaint requests.
Nothing GUI gets done while you are waiting on the lock.
Upvotes: 4