Java FX provides Window.centerOnScreen() to - guess what - center a window on a screen. HOWEVER, the Java FX' definition of "center of a screen" seems to be at (0.5x;0.33y). I hoped this was a bug, but I was told it's not.
Anyway. Has someone came up with a clean and easy solution on how to center a Window before displaying it? My first approach leads to flickering of the screen, since the window has to be displayed first, before it can be centered.
public static void centerOnScreen(Stage stage) {
stage.centerOnScreen();
stage.setY(stage.getY() * 3f / 2f);
}
Update: What I forgot to mention; I don't know the size of the window beforehand, so in order to center it manually I have to display it first - what causes it to flicker one time. So I'm looking for a solution to center it without displaying it first - like Java FX is able to do it, however the wrong way.
This is how you do it before the stage was made visible:
double width = 640;
double height = 480;
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
stage.setX((screenBounds.getWidth() - width) / 2);
stage.setY((screenBounds.getHeight() - height) / 2);
final Scene scene = new Scene( new Group(), width, height);
stage.setScene(scene);
stage.show();
and this after the stage was made visible, i. e. you can use the properties of the stage:
double width = 640;
double height = 480;
final Scene scene = new Scene( new Group(), width, height);
stage.setScene(scene);
stage.show();
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
stage.setX((screenBounds.getWidth() - stage.getWidth()) / 2);
stage.setY((screenBounds.getHeight() - stage.getHeight()) / 2);
If you have multiple screens, you can calculate the position manually using the list of Screen objects which is returned by the Screen.getScreens() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With