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