Dragon Dragon - 3 months ago 42
Java Question

JavaFX-2: how to get window size if it wasn't set manually?

I want to open a dialog window above the center of its parent window, so I use the following formula:

Window window = ((Node) actionEvent.getSource()).getScene().getWindow();
Scene scene = new Scene(new Group(new DialogWindow()));
Stage dialog = new Stage();
dialog.initOwner(window);
dialog.sizeToScene();

dialog.setX(stage.getX() + stage.getWidth() / 2 - dialog.getWidth() / 2); //dialog.getWidth() = NaN
dialog.setY(stage.getY() + stage.getHeight() / 2 - dialog.getHeight() / 2); //dialog.getHeight() = NaN

dialog.setScene(scene);
dialog.show(); //it is better to showAndWait();


I don't set size the manually because I need the window to be sized automatically to the size of its content.

Under Linux it sets window straight in the center of the parent window. But in Windows it doesn't work and leads to different results.

How can I get the dialog's width and height if I don't set them manually?

Answer

The width and height of Stage are calculated after it has been shown (.show()). Do the calculation after it:

...
dialog.show();
dialog.setX(stage.getX() + stage.getWidth() / 2 - dialog.getWidth() / 2); //dialog.getWidth() = not NaN
dialog.setY(stage.getY() + stage.getHeight() / 2 - dialog.getHeight() / 2); //dialog.getHeight() = not NaN

EDIT:
If showAndWait() is used instead of show(), then since showAndWait() blocks the caller event the calculations after the showAndWait() are also blocked. The one way of workaround could be doing calculation before in new Runnable:

final Stage dialog = new Stage();
dialog.initOwner(window);
dialog.initModality(Modality.WINDOW_MODAL);
dialog.sizeToScene();
dialog.setScene(scene);

Platform.runLater(new Runnable() {
    @Override
    public void run() {
        dialog.setX(primaryStage.getX() + primaryStage.getWidth() / 2 - dialog.getWidth() / 2); //dialog.getWidth() = NaN
        dialog.setY(primaryStage.getY() + primaryStage.getHeight() / 2 - dialog.getHeight() / 2); //dialog.getHeight() = NaN
    }
});
dialog.showAndWait();

Note also on initModality. The modality must be set in case of showAndWait(). Otherwise using showAndWait() has no sense.

Comments