I'm trying to make a custom blocking modal from another thread but can't understand how to go about it. Here is my modal:
public class BlockingModal extends JDialog {
private BlockingModal view;
public BlockingModal(JFrame parent) {
super(parent);
this.setModal(true);
}
public void showModal() {
BlockingModal view = this;
if (SwingUtilities.isEventDispatchThread()) {
view.setVisible(true);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
view.setVisible(true);
}
});
}
}
}
I was hoping that I would then be able to create a new instance of this modal from another thread and simply call myModal.showModal()
on it.
However, obviously, if it is called via invokeLater
then it is no longer blocking.
I'm trying to create a new piece of EDT compatible code within a large non-EDT codebase.
What is the best way to implement a blocking modal from another thread like this?
You should be able to use invokeAndWait
for this.
Otherwise, you'd have to use some kind of concurrency primitive (wait
and notify
, Condition
, etc.) to have the thread which calls showModal
wait until the event returns. invokeAndWait
already implements this for you, though, so it should work.