屏幕上的 JavaFX 中心舞台
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29558449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX center stage on screen
提问by Lars
I want to center a stage on the screen.
This is what I've tried:
我想在屏幕上居中放置一个舞台。
这是我尝试过的:
public class Test extends Application
{
@Override
public void start(final Stage primaryStage)
{
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.centerOnScreen();
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
After calling centerOnScreen() the stage is too high. It does not seem to work properly. Do I need to calulate the x and y pos myself? Or how do I use this function correctly?
调用 centerOnScreen() 后,舞台太高了。它似乎无法正常工作。我需要自己计算 x 和 y 位置吗?或者我如何正确使用这个功能?
采纳答案by ItachiUchiha
The default implementation of centerOnScreen()
is as follows :
的默认实现centerOnScreen()
如下:
Rectangle2D bounds = getWindowScreen().getVisualBounds();
double centerX = bounds.getMinX() + (bounds.getWidth() - getWidth())
* CENTER_ON_SCREEN_X_FRACTION;
double centerY = bounds.getMinY() + (bounds.getHeight() - getHeight())
* CENTER_ON_SCREEN_Y_FRACTION;
x.set(centerX);
y.set(centerY);
where
在哪里
CENTER_ON_SCREEN_X_FRACTION = 1.0f / 2;
CENTER_ON_SCREEN_Y_FRACTION = 1.0f / 3;
centerY
will always set the stage a little higher than the center.
centerY
总是将舞台设置得比中心高一点。
To position the stage at exact center, you can use your set your custom X and Y value.
要将舞台定位在精确的中心,您可以使用您设置的自定义 X 和 Y 值。
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction((ActionEvent event) -> {
System.out.println("Hello World!");
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
Rectangle2D primScreenBounds = Screen.getPrimary().getVisualBounds();
primaryStage.setX((primScreenBounds.getWidth() - primaryStage.getWidth()) / 2);
primaryStage.setY((primScreenBounds.getHeight() - primaryStage.getHeight()) / 2);
}
public static void main(String[] args) {
launch(args);
}
}