在秋千中使用sleep() [英] using sleep() in swing

查看:101
本文介绍了在秋千中使用sleep()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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");
   }
}

我希望节目节目 2秒后JButton(test2)。$
然后我在<$ c之后添加 thread.sleep(2000) $ c> test1 。

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

但我不知道为什么程序停止显示 test1 JButton
没有显示 test2 JButton 并且show test消息可以成功打印出来

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

推荐答案

简短的回答,不要。

Swing是一个单线程框架,这意味着任何阻止事件调度线程将阻止它更新UI或处理任何新事件(使您的UI看起来像挂起,因为它有)。

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).

当然,你可以使用 Thread ,但Swing也不是线程安全的。这意味着对UI的所有修改必须在事件调度线程的上下文中进行。虽然有办法克服这个问题,但最简单的方法是简单地使用Swing 计时器

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.

更接近请查看如何使用Swing Timers Swing中的并发了解更多详情

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

您还应该查看初始主题

更新用户界面时,可能需要调用 revaldiate 重绘添加新组件后强制UI更新以重新布局其内容。

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.

这篇关于在秋千中使用sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆