How to get parent Window in FXML Controller?

nvcnvn picture nvcnvn · Nov 27, 2012 · Viewed 24.8k times · Source

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?

Answer

Sergey Grinev picture Sergey Grinev · Nov 27, 2012

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

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