26

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?

nvcnvn
  • 4,991
  • 8
  • 49
  • 77

1 Answers1

53

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()
Dexter Legaspi
  • 3,192
  • 1
  • 35
  • 26
Sergey Grinev
  • 34,078
  • 10
  • 128
  • 141
  • 4
    Can this be done for a MenuItem? Your code gives this error for me: `Caused by: java.lang.ClassCastException: javafx.scene.control.MenuItem cannot be cast to javafx.scene.Node` – zygimantus Jun 08 '18 at 13:03
  • 7
    @zygimantus `((MenuItem)event.getTarget()).getParentPopup().getOwnerWindow()` – osvein Mar 13 '19 at 21:38