JavaFX: Fit child elements to HBox width


Is it possible to manage child elements in a HBox, so that the sum of the widths of all child elements is equal to the width of the HBox?

So that elements fill the HBox and no space is left.

The height of the child elements is by default the height of the HBox, so how about the width? I don't want to calculate the width in my program. It would be better if the layout does this automatically, so that no calculation is needed.

9/10/2017 11:29:23 PM

Accepted Answer

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.

2/27/2014 6:33:13 AM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow