Central JavaFX scene on screen

I want to focus the scene on the screen.
This is what I 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 scene is too high. It seems to be working incorrectly. Do I need to calculate x and y pos myself? Or how to use this function?

+7
java javafx
source share
1 answer

The standard implementation of centerOnScreen() 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 scene just above center.

To position the scene in the exact center, you can use your own set of X and Y values.

 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); } } 
+13
source share

All Articles