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);
Pay attention also to initModality . Modularity must be set in case of showAndWait() . Otherwise, using showAndWait() does not make sense.
source share