You should only be calling this method from the event dispatch thread, as this is the only thread that should interact with Swing components.
If you wish to pause background processing whilst awaiting user feedback I suggest you use a SwingWorker implementation whereby the doInBackground()
method periodically calls publish()
, allowing process()
to be called on the Swing thread. doInBackground()
can then potentially block until some action is taken within process()
. For example:
new SwingWorker<Void, Void>() {
private volatile boolean done;
// Called on background thread
public void doInBackground() {
for (int i=0; i<1000000; ++i) {
// Do work
if (i % 1000 == 0) {
publish(); // Will cause process() to be called on Event Dispatch thread.
synchronized(this) {
wait();
}
if (done) {
System.err.println("Background thread stopping.");
return null;
}
}
}
}
// Called on Event dispatch thread.
protected void process(List<Void> chunks) {
if (JOptionPane.showConfirmDialog(getFrame(),
"Do you want to quit?", "Confirm Quit",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
done = true;
}
synchronized(this) {
notifyAll();
}
}
}.execute();