Share the post "How To Create Modal Stage Window From A JFrame In Java FX 2"
Well, there is no solution to making a Stage window modal when opened from a JFrame. At least not directly. I scoured through countless forums and blog posts but their solutions never made it modal.
A future version of Java FX may solve this problem. In the meantime, this is how I did it in Java FX 2. The same JDialog will be instantiated but set to invisible. I did this by calling the setUndecorated() method to true.
Within the JDialog class, that is where I called the Java FX code to open a Stage window dialog.
So now it is modal. But when you click the JFrame in the task bar in the Windows OS below, the Stage window is not sent to the front. This is not the behavior we want for a modal window, right?
What I did was to add a FocusListener in the JDialog custom class so that when it is in focus (since it is modal), it will call the Stage window object and send it to the front.
Here is the custom JDialog class I made.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class MyDialog extends JDialog { private StageModalDialog smd; public MyDialog(JFrame frame) { super(frame, "Stage Modal Dialog", true); setResizable(false); setSize(0, 0); setUndecorated(true); new JFXPanel(); Platform.runLater(new Runnable() { @Override public void run() { smd = new StageModalDialog(); smd.showAndWait(); } }); addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent fe) { if (smd != null && smd.isShowing()) smd.toFront(); } }); setVisible(true); } } |
Then just call that from within your JFrame.
The StageModalDialog class is a custom class I made that inherits from the Stage class.