YWX
YWX

Reputation: 33

using sleep() in swing

public class TestFrame extends JFrame
{
   public TestFrame()
   {

        setBounds(10, 10, 500, 500);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(3);       
   }

   public static void main(String[] args) throws InterruptedException
   {
        TestFrame tf = new TestFrame();
        tf.add(new JButton("test1"));
        tf.setVisible(true);
        Thread.sleep(2000);
        tf.getContentPane().removeAll();
        tf.add(new JButton("test2"));
        System.out.print("Show test");
   }
}

I want the program show JButton("test2") after 2 seconds.
Then I add thread.sleep(2000) after test1.

But I don't know why the program stops at showing the test1 JButton, not showing test2 JButton and the "show test" message can sucess print out

Upvotes: 1

Views: 1269

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

Short answer, don't.

Swing is a single threaded framework, this means that any thing that blocks the Event Dispatching Thread will prevent it from updating the UI or processing any new events (making your UI look like it's hung, cause it has).

Sure, you could use a Thread, but Swing is also not thread safe. This means that ALL modifications to the UI MUST be made from within the context of the Event Dispatching Thread. While there are ways to overcome this, the easiest way is to simply use a Swing Timer.

Take a closer look at How to use Swing Timers and Concurrency in Swing for more details

You should also take a look at Initial Threads.

When updating the UI, it may be required to call revaldiate and repaint after you have added the new components to force the UI to update to re-layout it's contents.

Upvotes: 5

Related Questions