问题描述
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();
这一点在舞台上可见之后,我。即你可以使用舞台的属性:
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对象列表手动计算位置通过方法。
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中正确居中窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!