The default implementation of centerOnScreen()
is as follows :
Rectangle2D bounds = getWindowScreen().getVisualBounds();
double centerX = bounds.getMinX() + (bounds.getWidth() - getWidth())
* CENTER_ON_SCREEN_X_FRACTION;
double centerY = bounds.getMinY() + (bounds.getHeight() - getHeight())
* CENTER_ON_SCREEN_Y_FRACTION;
x.set(centerX);
y.set(centerY);
where
CENTER_ON_SCREEN_X_FRACTION = 1.0f / 2;
CENTER_ON_SCREEN_Y_FRACTION = 1.0f / 3;
centerY
will always set the stage a little higher than the center.
To position the stage at exact center, you can use your set your custom X and Y value.
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction((ActionEvent event) -> {
System.out.println("Hello World!");
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
Rectangle2D primScreenBounds = Screen.getPrimary().getVisualBounds();
primaryStage.setX((primScreenBounds.getWidth() - primaryStage.getWidth()) / 2);
primaryStage.setY((primScreenBounds.getHeight() - primaryStage.getHeight()) / 2);
}
public static void main(String[] args) {
launch(args);
}
}