how to position the window stage in javafx?
Asked Answered
W

1

7

I made a simple game and when it ends it'll display a new Stage with some information:

 public static void d(String m){
    Stage stage = new Stage();
    stage.setTitle("GAME FINISHED");
    Label label = new Label(m);
    label.setTextFill(Color.PURPLE);
    label.setFont(new Font("Cambria",14));

    Button button = new Button("Close");
    VBox vb = new VBox();
    button.setOnAction(e-> p.close());
    vb.getChildren().addAll(label,button);
    vb.setSpacing(50);
    vb.setPadding(new Insets(5,0,0,12));
    Scene scene = new Scene(v,200,300);
    stage.setScene(scene);
    stage.setResizable(false);
    stage.showAndWait();
}

I don't want this window to show in the middle of the screen because it hides some content of the game. Is it possible to display a stage not in the middle of the screen?

Warfold answered 14/3, 2019 at 21:30 Comment(0)
C
13

You can use the stage.setX() and stage.setY() methods to set the window position manually:

// create and init stage
stage.setX(200);
stage.setY(200);
stage.showAndWait();

If you want to calculate the position based on the screen size you can use the following to get the size:

Rectangle2D bounds = Screen.getPrimary().getVisualBounds();

If you want to use stage.getWidth() or stage.getHeight() to calculate the position you have to show the stage before:

stage.show();
Rectangle2D bounds = Screen.getPrimary().getVisualBounds();
double x = bounds.getMinX() + (bounds.getWidth() - scene.getWidth()) * 0.3;
double y = bounds.getMinY() + (bounds.getHeight() - scene.getHeight()) * 0.7;
stage.setX(x);
stage.setY(y);

In this case you should use stage.show() instead of stage.showAndWait().

Chartist answered 14/3, 2019 at 21:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.