如何在 Java FX 中正确居中窗口? [英] How to center a window properly in Java FX?

查看:62
本文介绍了如何在 Java FX 中正确居中窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java FX 提供 Window.centerOnScreen() 来 - 猜猜是什么 - 在屏幕上居中显示窗口.但是,Java FX 对屏幕中心"的定义似乎是 (0.5x;0.33y).我希望这是一个错误,但 有人告诉我不是.

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);
}

更新:我忘记提及的;我事先不知道窗口的大小,因此为了手动将其居中,我必须先显示它 - 是什么导致它闪烁一次.所以我正在寻找一种解决方案来将它居中而不先显示它 - 就像 Java FX 能够做到这一点,但是方式是错误的.

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();

在舞台可见之后,我.e.您可以使用舞台的属性:

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);  

如果您有多个屏幕,您可以使用 Screen.getScreens() 方法.

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.

这篇关于如何在 Java FX 中正确居中窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆