Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to position the window stage in javafx?

Tags:

java

javafx

stage

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?

like image 409
Ehsan Duwidi Avatar asked Mar 14 '19 21:03

Ehsan Duwidi


People also ask

How do you set a scene in a stage?

You can add a Scene object to the stage using the method setScene() of the class named Stage.

How do I make my JavaFX window full screen?

The following methods can be used on the stage : setMaximized(boolean) - To maximize the stage and fill the screen. setFullScreen(boolean) - To set stage as full-screen, undecorated window.

Which method is used to make a JavaFX stage visible?

The show() method returns immediately regardless of the modality of the stage. Use the showAndWait() method if you need to block the caller until the modal stage is hidden (closed). The modality must be initialized before the stage is made visible.


1 Answers

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().

like image 192
Samuel Philipp Avatar answered Sep 22 '22 13:09

Samuel Philipp