如何在setBounds的情况下暂停进程

时间:2016-01-23 16:50:30

标签: java multithreading sleep setbounds

我想在按下按钮时显示标签的移动一段时间。请帮忙。 只是告诉我如何在更改setBounds期间暂停该过程一段时间,在这种情况下,sleep方法会暂停该过程,但最后只执行setBound语句:

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 个答案:

答案 0 :(得分:1)

阅读swing concurrency tutorial。经验法则:

  • 您可能无法在事件发送线程中睡眠,因为它会冻结UI
  • 您可能无法访问事件派发线程以外的线程中的swing组件

所以,你需要一个单独的线程来休眠,然后要求EDT修改标签的边界。

使用swing计时器,或从后台线程中调用SwingUtilities.invokeLater(),以便修改标签边界的任务由EDT完成。

另请注意,sleep()是一种静态方法。应使用Thread.sleep()而不是b.sleep()来调用它。