Home > Blockchain >  Disabling a JFrame not through Modality
Disabling a JFrame not through Modality

Time:06-28

I need my JFrame to freeze/ become inaccessible, similar to how it would with a model JDialog or setEnabled(false).
In most cases I would use JDialog but in this instance I am running a dialog through a C library.
Going down the setEnabled(false) line also doesn't work because it, on setEnabled(true), will send the window to the back. And even using toFront() will cause the window to go to the back for a split second then come to the front again.
Is there a better way to go about doing this, or an I stuck with the slight imperfection of the window flickering.

Also if you are familiar with the library I am using LWJGL's NativeFileDialog wrapper.

CodePudding user response:

I have found a pretty good solution to this issue, originally answered as part of this post. It takes the idea of using a JDialog, but instead of displaying some message it is completely transparent, invisible to the user.

final JDialog modalBlocker = new JDialog();
modalBlocker.setModal(true);
modalBlocker.setUndecorated(true);
modalBlocker.setOpacity(0.0f);
modalBlocker.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

Then we can simply display our modal and show our file dialog

// Using invoke later we show our dialog after our frame has been blocked
// by setVisible(true)
SwingUtilities.invokeLater(()->{
    // show dialog
});
modalBlocker.setVisible(true);
modalBlocker.dispose(); // immediately release resources

Then we can call modalBlocker.setVisible(false) at any point to stop the modality effect on our frame.

Again this is the solution that worked for me, it is not mine. The code was written to integrate JavaFX with Swing by Sergei Tachenov, all credit goes to him!

  • Related