JavaFX-2: how to get window size if it has not been set manually?

I want to open a dialog box 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 do not set the size manually, because I need the window to automatically determine the size of its contents.

On Linux, it sets the window right in the center of the parent window. But on Windows this does not work and leads to different results.

How can I get the width and height of the dialog if I do not set them manually?

+4
source share
2 answers

Stage width and height are calculated after it has been shown ( .show() ). Perform 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() show() used instead of show() , then since showAndWait() blocks the caller's event, the calculations after showAndWait() also blocked. One workaround could be done earlier than in the 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(); 

Pay attention also to initModality . Modularity must be set in case of showAndWait() . Otherwise, using showAndWait() does not make sense.

+10
source

Try the following:

 Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); <br> System.out.println(screenBounds.getHeight()); <br> System.out.println(screenBounds.getWidth()); 
0
source

All Articles