JavaFX: Fit child elements to HBox width
In FXML
:
<HBox>
<Label HBox.hgrow="ALWAYS" maxWidth="Infinity">
TEST
</Label>
</HBox>
It depends what kind of children does the HBox
contain. Some of the children may not be resizable nodes. However, generally speaking, you can use HBox.setHgrow()
method and set the same Priority
for all children of hbox. The explanation is in its javadoc:
Sets the horizontal grow priority for the child when contained by an hbox. If set, the hbox will use the priority to allocate additional space if the hbox is resized larger than it's preferred width. If multiple hbox children have the same horizontal grow priority, then the extra space will be split evening between them. If no horizontal grow priority is set on a child, the hbox will never allocate it additional horizontal space if available. Setting the value to null will remove the constraint.
Additionally, if you are trying to obtain a grid-like layout then try out other layout options, for instance TilePane
or FlowPane
and maybe GridPane
.
The simple code for your answer would be this:
Button button1 = new Button("Save");
Button button2 = new Button("Delete");
HBox.setHgrow(button1, Priority.ALWAYS);
HBox.setHgrow(button2, Priority.ALWAYS);
It's recommended to use HBox class rather than name of HBox pane.
Adding to @bdshahab's answer, since HBox will try to resize their children to their preferred widths, they will only fill the box if their combined preferred widths are wider than the HBox width.
So it may be necessary to do something like:
Button button1 = new Button("Save");
Button button2 = new Button("Delete");
HBox.setHgrow(button1, Priority.ALWAYS);
HBox.setHgrow(button2, Priority.ALWAYS);
button1.setPrefWidth(100000);
button2.setPrefWidth(100000);