How to pause the process in case of setBounds

59 views Asked by At

I want to show movement of label for a while on pressing of button. Please help. Just tell me how I pause the process for a while during the changing of setBounds, in this case sleep method pauses the process but just last setBound statement executes only:

void ActionPerformed(..){
    Thread b = new Thread();

        try{
            label.setBounds(100,150,70,70);

            b.sleep(1000);
            label.setBounds(100,200,70,70);

            b.sleep(1000);
            label.setBounds(100,150,70,70);

        }catch(InterruptedException e){
            e.printStackTrace();
        }
}
1

There are 1 answers

0
JB Nizet On

Read the swing concurrency tutorial. Rule of thumbs:

  • you may not sleep in the event dispatch thread, because it freezes the UI
  • you may not access swing components in a thread other than the event dispatch thread

So, you need a separate thread that sleeps, and then asks the EDT to modify the bounds of the label.

Use a swing Timer, or call SwingUtilities.invokeLater() from your background thread so that the task of modifying the bounds of the label is done by the EDT.

Also, note that sleep() is a static method. It should be called using Thread.sleep(), not b.sleep().