Search code examples
javafx-2fxml

How to get parent Window in FXML Controller?


For example, I want open a DirectoryChooser when clicking on the button:

<VBox fx:controller="com.foo.MyController"
    xmlns:fx="http://javafx.com/fxml">
    <children>
        <Button text="Click Me!" onAction="#handleButtonAction"/>
    </children>
</VBox>

And the Controller class:

package com.foo;

public class MyController {
    public void handleButtonAction(ActionEvent event) {
        DirectoryChooser dc = new DirectoryChooser();
        File folder = dc.showDialog(null);//I want to put the WIndows here.
    }
}

I want to put the main Window to the ShowDialog so that it will be blocked but how can I access it?


Solution

  • You can ask any node for the Scene and then call Scene#getWindow().

    ((Node) event.getTarget()).getScene().getWindow()
    

    From @osvein if this is a handler for a MenuItem it should be:

    ((MenuItem) event.getTarget()).getParentPopup().getOwnerWindow()