I created this JavaFX dialog with Close button:
final int xSize = 300;
final int ySize = 280;
final Color backgroundColor = Color.WHITE;
final String text = "SQL Browser Version 1.0";
final Stage aboutDialog = new Stage();
aboutDialog.initModality(Modality.WINDOW_MODAL);
Button closeButton = new Button("Close");
closeButton.setAlignment(Pos.BOTTOM_CENTER);
closeButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
aboutDialog.close();
}
});
Scene aboutDialogScene = new Scene(VBoxBuilder.create()
.children(new Text(text), closeButton)
.alignment(Pos.CENTER)
.padding(new Insets(10))
.build(), xSize, ySize, backgroundColor);
aboutDialog.setScene(aboutDialogScene);
aboutDialog.show();
I want to display the button at the bottom of the dialog. I used this to set the alignment:
closeButton.setAlignment(Pos.BOTTOM_CENTER);
but for some reason the button is displayed at the center of the dialog. Can you tell me how I can fix this?
If you want to use a
VBox
for this, the method you are looking for is:VBox.setVgrow(node, Priority.ALWAYS);
By default a VBox will just place children one under the other from the top left of where you place it. The children don't expand to fill all of the available vertical area, unless you set a Vgrow constraint on a child with an unbounded max height.
A few different ways you can get the layout you seek (there are others as well):
StackPane
instead of aVBox
and align your button withStackPane.setAlignment(closeButton, Pos.BOTTOM_CENTER);
AnchorPane
instead of aVBox
and set constraints on theAnchorPane
appropriately.Sample spring region:
Calling
closeButton.setAlignment(Pos.BOTTOM_CENTER);
sets the alignment of things (text and graphic) within the closeButton, not the alignment of the closeButton within it's parent (which is what you really want).For understanding how layout constraints work, SceneBuilder is a good tool to play around with and ScenicView can help debug layout issues in existing code.
Here are a few FXML samples of your layout that you can load up into SceneBuilder to see how the different layout options work.
All of the samples below can easily be written in plain java using the JavaFX API if you prefer. I wrote them in fxml as it makes the layouts easy to preview in SceneBuilder.
FXML sample using a StackPane:
And the same thing with some spring regions:
And the same thing with the label itself set to expand to fill empty space in the VBox: