本文介绍了JavaFX中心舞台在屏幕上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在屏幕上占据一个舞台。

这是我尝试过的:

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

调用centerOnScreen()后,舞台太高了。它似乎没有正常工作。我是否需要自己制作x和y pos?或者我如何正确使用此功能?

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()的默认实现如下:

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

其中

CENTER_ON_SCREEN_X_FRACTION = 1.0f / 2;
CENTER_ON_SCREEN_Y_FRACTION = 1.0f / 3;

centerY 将始终设置一个阶段高于中心。

centerY will always set the stage a little higher than the center.

要将舞台定位在确切的中心位置,您可以使用自定义X和Y值设置

To position the stage at exact center, you can use your set your custom X and Y value.

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

这篇关于JavaFX中心舞台在屏幕上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-23 04:24