How to Use the HBox Layout in JavaFX

By Doug Lowe

The HBox class provides one of the simplest of all JavaFX’s layout managers: It arranges one or more nodes into a horizontal row. This table presents the most commonly used constructors and methods of the HBox class.

HBox Constructors and Methods
Constructor Description
HBox() Creates an empty HBox.
HBox(double spacing) Creates an empty HBox with the specified spacing.
HBox(Node… children) Creates an HBox with the specified child nodes. This constructor lets you create an HBox and add child nodes to it at the same time.
HBox(double spacing, Node… children) Creates an HBox with the specified spacing and child nodes.
Method Description
ObservableList<Node> getChildren() Returns the collection of all child nodes that have been added to the HBox. The collection is returned as an ObservableList type, which includes the method addAll, letting you add one or more nodes to the list.
static void setAlignment(Pos alignment) Sets the alignment for child nodes within the HBox.
static void setHgrow(Node child, Priority priority) Sets the growth behavior of the given child node.
static void setMargin(Node child, Insets value) Sets the margins for a given child node.
void setPadding(Insets value) Sets the padding around the inside edges of the Hbox.
void setSpacing(double value) Sets the spacing between nodes displayed within the HBox.

The HBox class is defined in the javafx.scene.layout package, so you should include the following import statement in any program that uses an HBox:

import javafx.scene.layout.*;

The easiest way to create an HBox is to first create the nodes that you want to place in the HBox and then call the HBox constructor and pass the nodes as arguments. For example:

Button btn1 = new Button(“Button One”);

Button btn2 = new Button(“Button Two”);

Button btn3 = new Button(“Button Three”);

HBox hbox = new HBox(btn1, btn2, btn3);

If you prefer to create the HBox control in an initially empty state and later add the controls, you can do so like this:

HBox hbox = new HBox();

Hbox.getChildren().addAll(btn1, btn2, btn3);

Here, the getChildren method is called, which returns a collection of all the children added to the HBox pane. This collection is defined by the class ObservableList, which includes a method named addAll that you can use to add one or more nodes to the list.