问题
I have a SwingWorker thread that launches a modal dialog box (from a property change listener that listens to the StateValue of started) and the swing worker proceeds to do its work. However, it looks like the done method is not called because that is called on the EDT but the swing worker's modal dialog is blocking the EDT. So, I can't close the dialog from the EDT (or from the done method). Right now I'm just closing the dialog from the doInBackground at the end of that method, but that seems a little unsafe from the doInBackground since it's not on the EDT. What's the best way to handle this? thanks.
回答1:
The dispatch loop should continue to dispatch the events associated with SwingWorker
even when a modal dialog is displayed.
This works for me.
import javax.swing.*;
public class Unions {
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
runEDT();
}});
}
private static void runEDT() {
final JDialog dialog = new JDialog((JFrame)null, true);
new SwingWorker<Void,Void>() {
@Override protected Void doInBackground() throws Exception {
// But this is working.
Thread.sleep(3000);
return null;
}
@Override protected void done() {
dialog.setVisible(false);
}
}.execute();
dialog.setVisible(true);
}
}
回答2:
For reference:
When a modal dialog is launched in Swing, the execution of that thread is stopped until the dialog is closed.
This is why your done() method was never called (doInBackground() couldn't finish and done() is only called after that).
Opening a modal-dialog from an action called by the EDT thread is slightly different. The EDT itself will continue to process events but the actual event thread code (the code of the action) which opens the modal dialog still gets blocked (and waits until the dialog is closed).
Naturally, in case of non-modal dialogs, this problem never surfaces.
By the way: You should never open a dialog from outside the EDT. If the decision is made on a non-EDT thread, you need to use SwingUtilities.invokeLater() to actually open the dialog.
Sounds complicated but it is actually not, once you master the concept of the EDT.
来源:https://stackoverflow.com/questions/1925656/swing-worker-modal-dialog-wont-close