How to create a modal window in JavaFX 2.1

I can't figure out how to create a modal window in JavaFX. Basically I have file chooser and I want to ask the user a question when they select a file. I need this information in order to parse the file, so the execution needs to wait for the answer.

I've seen this question but I've not been able to find out how to implement this behavior.


In my opinion this is not good solution, because parent window is all time active.
For example if You want open window as modal after click button...

private void clickShow(ActionEvent event) {
    Stage stage = new Stage();
    Parent root = FXMLLoader.load(
        YourClassController.class.getResource("YourClass.fxml"));
    stage.setScene(new Scene(root));
    stage.setTitle("My modal window");
    stage.initModality(Modality.WINDOW_MODAL);
    stage.initOwner(
        ((Node)event.getSource()).getScene().getWindow() );
    stage.show();
}

Now Your new window is REALY modal - parent is block. also You can use

Modality.APPLICATION_MODAL

Here is link to a solution I created earlier for modal dialogs in JavaFX 2.1 The solution creates a modal stage on top of the current stage and takes action on the dialog results via event handlers for the dialog controls.

JavaFX 8+

The prior linked solution uses a dated event handler approach to take action after a dialog was dismissed. That approach was valid for pre-JavaFX 2.2 implementations. For JavaFX 8+ there is no need for event handers, instead, use the new Stage showAndWait() method. For example:

Stage dialog = new Stage();

// populate dialog with controls.
...

dialog.initOwner(parentStage);
dialog.initModality(Modality.APPLICATION_MODAL); 
dialog.showAndWait();

// process result of dialog operation. 
... 

Note that, in order for things to work as expected, it is important to initialize the owner of the Stage and to initialize the modality of the Stage to either WINDOW_MODAL or APPLICATION_MODAL.

There are some high quality standard UI dialogs in JavaFX 8 and ControlsFX, if they fit your requirements, I advise using those rather than developing your own. Those in-built JavaFX Dialog and Alert classes also have initOwner and initModality and showAndWait methods, so that you can set the modality for them as you wish (note that, by default, the in-built dialogs are application modal).