How to create a modal window in JavaFX 2.1

Luka picture Luka · May 7, 2012 · Viewed 81.1k times · Source

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.

Answer

Krzysztof Szewczyk picture Krzysztof Szewczyk · Apr 12, 2013

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