【发布时间】:2013-12-14 15:58:51
【问题描述】:
问题是这样的:
我有一个正在运行的摇摆应用程序,在某个时候对话框需要插入用户名和密码并按“确定”。
我希望当用户按“确定”时,swing 应用程序按以下顺序执行:
- 打开“请稍候”JDialog
- 进行一些操作(最终显示一些其他的 JDialog 或 JOptionPane)
- 当它完成操作时关闭“请稍候”JDialog
这是我在okButtonActionPerformed()中写的代码:
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
//This class simply extends a JDialog and contains an image and a jlabel (Please wait)
final WaitDialog waitDialog = new WaitDialog(new javax.swing.JFrame(), false);
waitDialog.setVisible(true);
... //Do some operation (eventually show other JDialogs or JOptionPanes)
waitDialog.dispose()
}
这段代码显然不起作用,因为当我在同一个线程中调用 waitDialog 时,它会阻塞所有代码,直到我不关闭它。
所以我尝试在不同的线程中运行它:
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
//This class simply extends a JDialog and contains an image and a jlabel (Please wait)
final WaitDialog waitDialog = new WaitDialog(new javax.swing.JFrame(), false);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
waitDialog.setVisible(true);
}
});
... //Do some operation (eventually show other JDialogs or JOptionPanes)
waitDialog.dispose()
}
但这也不起作用,因为 waitDialog 不会立即显示,而是在操作完成之后才显示(当他们显示 joption 窗格“您以...登录”时)
我也尝试使用 invokeAndWait 而不是 invokeLater 但在这种情况下它会引发异常:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread
我该怎么办?
【问题讨论】:
标签: java multithreading swing event-dispatch-thread