How to open modal dialog from JFXPanel in JavaFX?

2019-07-20 06:30发布

问题:

To show modal dialog following code should be used:

val dialogStage:Stage = new Stage();
dialogStage.initOwner(ownerStageWindow)
dialogStage.initModality(javafx.stage.Modality.WINDOW_MODAL);
val scene = new Scene(...)
dialogStage.setScene(scene)
dialogStage.show();

But where and how to get owner stage?
There is no primary stage if I use JFXPanel as root component to embed JavaFX application.

回答1:

Pass a null value to initOwner (as your dialog is APPLICATION_MODAL, not WINDOW_MODAL, the side-effects of this are likely not too drastic).

OR

Create a JFrame with another JFXPanel in it for your dialog scene.



回答2:

To get the stage of a JFXPanel:

Field f = JFXPanel.class.getDeclaredField("stage");
f.setAccessible(true);
stage = (Window)f.get(fxPanel);

But it is important to note that what you get will not be necessarily be an instance of Stage. It will be an instance of Window (superclass of Stage). In the case of a swing application, it will return an EmbeddedWindow instance (which is not a Stage).

Or to state this technical answer otherwise: You will only have a Stage if you have a pure JavaFx application. Please correct me if I'm wrong.

So, to display your modal window, you could pass the instance of Window as shown in the code sample or pass a null.