java界面居中,如何在Java FX中正确居中窗口?

本文讨论了JavaFX中Stage.centerOnScreen()方法存在的问题,它将窗口中心定义为屏幕的(0.5x;0.33y)位置。作者遇到窗口闪烁的问题,因为必须先显示窗口才能进行居中。解决方案分为两种情况:一种是在舞台可见前通过计算屏幕边界来设置位置;另一种是在舞台显示后调整位置。文章提供了具体的代码示例来解决这个问题。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值