在swing中使用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")
。
然后我在test1
之后添加thread.sleep(2000)
。
但我不知道为什么程序停止显示test1 JButton
,没有显示test2 JButton
并且“show test”消息可以成功打印出来
简短的回答,不要。
Swing是一个单线程框架,这意味着阻止事件调度线程的任何东西都会阻止它更新UI或处理任何新事件(使你的UI看起来像是挂起的,因为它有)。
当然,你可以使用一个Thread
,但Swing也不是线程安全的。 这意味着对UI的所有修改必须在事件调度线程的上下文中进行。 虽然有办法克服这个问题,但最简单的方法是简单地使用Swing Timer
。
详细了解如何 在Swing中 使用Swing Timers和Concurrency以获取更多详细信息
您还应该看一下Initial Threads 。
更新UI时,可能需要在添加新组件后调用revaldiate
和repaint
以强制UI更新以重新布局其内容。