問題是這樣的:
我有一個swing應用程序正在運行,在某個時候對話框需要插入用戶名和密碼並按「ok」。
我想,當用戶按下「OK」 Swing應用程序確實順序:製作顯示「Please Wait」的擺動線程JDialog
- 打開「請等待」的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
我怎樣才能做?
它似乎工作,謝謝(也感謝@Elias):)。 但現在還有一個小問題。當關閉主應用程序(使用dispose())時,SwingWorker線程繼續運行。我是否明確地關閉它?它是否在達到doInBackground的返回聲明時終止? – user2572526
@ user2572526:是的,它會在完成時自動關閉。你怎麼知道它仍在運行? –
我解決了,這不是SwingWorker的問題,它是JDialog初始化的錯誤。 (我肯定它仍然由Netbeans分析器運行)。 非常感謝您的幫助。 – user2572526