【发布时间】:2014-06-02 06:27:24
【问题描述】:
我有一个 Swing 应用程序,我希望在其中添加一些延迟。我有一个关闭按钮,单击该按钮应显示 JTextArea,其中显示“正在关闭数据库连接....”,然后执行 Database.databaseClose() 方法和 System.exit()。我已经尝试使用 Thread.sleep() 方法,如下面的代码中的延迟。当我执行程序时,屏幕冻结 2 秒,然后关闭而不显示 JTextArea。关闭按钮和 JTextArea 直接添加到 JFrame 中。
我想要的是,在单击关闭按钮时,应立即显示 JTextArea,然后应用程序应延迟 2 秒,然后最终实现 Database.databaseClose() 方法并退出程序。 Database.databaseClose() 方法工作得很好。
我是 Swings 的初学者,如果有人可以修改代码以实现上述要求,我将不胜感激。谢谢!
这里是sn-p的代码:
JButton btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JTextArea txtrClosingDatabaseConnections = new JTextArea();
txtrClosingDatabaseConnections.setText("\r\n\tClosing database connections....");
getContentPane().add(txtrClosingDatabaseConnections);
validate();
repaint();
/*
try
{
Thread.sleep(2000);
}
catch (InterruptedException e2)
{
e2.printStackTrace();
}
*/
try
{
Database.databaseClose();
}
catch (Exception e1)
{
e1.printStackTrace();
}
System.exit(0);
}
});
getContentPane().add(btnClose);
【问题讨论】:
-
我尝试使用 Thread 方法 sleep()。但它会在指定时间冻结 GUI 屏幕并退出。 JTextArea 永远不会显示