Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX center stage on screen [duplicate]

Tags:

java

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

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?

like image 847
Lars Avatar asked Apr 10 '15 09:04

Lars


1 Answers

The default implementation of centerOnScreen() is as follows :

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.

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);
    }
}
like image 68
ItachiUchiha Avatar answered Sep 25 '22 02:09

ItachiUchiha