JavaFX 2.2 Modal window dialog *with* FXML

2019-04-09 15:30发布

问题:

I am trying to use the example provided by @jewelsea at this gist and I'm stuck because I'm using FXML.

I have seen both of these posts: How to create a modal window in JavaFX 2.1 and this answer to JavaFX 2 modal window.

Where I'm stuck is in the code by jewelsea, where it says:

final WebView webView = new WebView(); 
webView.getEngine().load("http://docs.oracle.com/javafx/");
primaryStage.setScene(new Scene(webView));

Whereas, since I'm using FXML, I do this:

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("MyFXML.fxml"));
Scene scene = (Scene)fxmlLoader.load();
myController = fxmlLoader.getController();
primaryStage.setScene(scene);

Can you tell me how to modify my code (the 4 lines above), so it works with jewelsea's example?

Thanks!

回答1:

The replacement code you are using via FXMLLoader rather than the WebView created scene sample code is fine, you don't need to modify it.

Your code will display the main scene for your primary stage based on an fxml document (for my sample I was using a WebView as my main scene, which you don't need, so you don't need any of the WebView related code from the gist).

What you need is some trigger in your controller at the time you want to display a dialog. As a simple example, you can setup an fxml for your main scene which just includes a button, and then supply an ActionHandler for the button in your controller (just like in the Introduction to FXML document).

Now, instead of just doing a println when the button is pressed as Introduction to FXML has, call the dialog.show() method like the gist did at the time of WebView document load. What should happen is that the dialog will now be displayed on top of your fxml generated scene.

You will notice that the dialog itself contains a Scene. If you wanted (and this is optional), you could define the scene contents using fxml. To do this, at the time of dialog construction, you set up a new fxml and new controller for the dialog contents and load the fxml created scene for the dialog into the dialog's stage. The code to do this is pretty much identical code to what you used to load the main scene's fxml into the primaryStage.

Try the above and see if it works for you. If you are still stuck I can probably create an fxml specific example of the gist along the lines of this answer.

Also note that the referenced gist was written a while ago, and there is a now a showAndWait method in JavaFX which facilitates blocking execution of code when making a dialog call and then allowing to process the result of the dialog without using some of the event handler mechanisms from the gist example. Strategies both with and without showAndWait are perfectly acceptable solutions though.