Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

javafx - How to center a window properly in Java FX?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...