I am having a problem centering a button in my borderpane to be centered according to the stage. It is centered according to the borderpane but I want it to be in the exact center of the window.
I am referring to the bottom part of my picture which has the play button and difficulty choiceBox.
I am using a borderpane to have the difficulty part be on the right side and the play button in the center.
As you can see, play is not centered in the picture.
I would like to do that but I'm not sure how. I think that I could possibly set the width of my left node to be equal to my right node but I don't have anything for my left Node.
// bottom section for positioning
BorderPane settings = new BorderPane();
settings.setPadding(new Insets(10));
// play button
Button playBtn = new Button("Play");
settings.setCenter(playBtn);
// difficulty options
Label diffLabel = new Label("Difficulty: ");
ChoiceBox<String> diffBox = new ChoiceBox<String>(FXCollections.observableArrayList(
"Easy", "Standard", "Hard"
));
diffBox.getSelectionModel().select(1);
// for wrapping the diffuclty.
HBox difficulty = new HBox(diffLabel, diffBox);
difficulty.setAlignment(Pos.CENTER);
difficulty.setSpacing(10);
settings.setRight(difficulty);
One of the possibilities is to add a Region
to the left side of the BorderPane
to act like a spacer.
From the doc of BorderPane
:
The left and right children will be resized to their preferred widths and extend the length between the top and bottom nodes. And the center node will be resized to fill the available space in the middle.
Therefore adding a spacer with the same width as the HBox
on the right side should solve the problem:
Region padderRegion = new Region();
padderRegion.prefWidthProperty().bind(difficulty.widthProperty());
settings.setLeft(padderRegion);
Here the width of the left spacer is bound to the width of the HBox
on the right side, therefore the centered Node
(the play button) will be centered on the screen.
Another possibility is to use various padders within a HBox
:
HBox bottomPanel = new HBox();
bottomPanel.setAlignment(Pos.CENTER);
Region padderRegion1 = new Region();
Region padderRegion2 = new Region();
Region padderRegion3 = new Region();
padderRegion1.prefWidthProperty().bind(diffLabel.widthProperty().add(diffBox.widthProperty()));
bottomPanel.getChildren().addAll(padderRegion1, padderRegion2, playBtn, padderRegion3, diffLabel, diffBox);
HBox.setHgrow(padderRegion2, Priority.ALWAYS);
HBox.setHgrow(padderRegion3, Priority.ALWAYS);