How to Use the VBox Layout in JavaFX

By Doug Lowe

The VBox class is similar to the HBox class in JavaFX, but instead of arranging nodes horizontally in a row, it arranges them vertically in a column. This table shows the most commonly used constructors and methods of the VBox class.

VBox Constructors and Methods
Constructor Description
VBox() Creates an empty VBox.
VBox(double spacing) Creates an empty VBox with the specified spacing.
VBox(Node… children) Creates an VBox with the specified child nodes. This constructor lets you create a VBox and add child nodes to it at the same time.
VBox(double spacing, Node… children) Creates a VBox 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 VBox. 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 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 VBox.
static void setVgrow(Node child, Priority priority) Sets the growth behavior of the given child node.

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

import javafx.scene.layout.*;

Here’s an example that creates three buttons and uses a VBox to arrange them into a column:

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

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

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

VBox vbox = new VBox(btn1, btn2, btn3);

You can accomplish the same thing by using the default constructor and calling the getChildren method, as in this example:

VBox vbox = new VBox();

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

As with the HBox class, you can use spacing, padding, margins, and spacer nodes to control the spacing of nodes within a VBox. Here’s an example that sets 10 pixels of vertical space between nodes and 10 pixels of padding on each edge of the pane:

Button btn1 = new Button(“One”);

Button btn2 = new Button(“Two”);

Button btn3 = new Button(“Three”);

VBox vbox = new VBox(10, btn1, btn2, btn3);

vbox.setPadding(new Insets(10));

Here’s an example that creates a column of three buttons, with one button at the top of the column and two at the bottom, with 10 pixels of spacing and padding:

// Create the buttons

Button btn1 = new Button(“One”);

Button btn2 = new Button(“Two”);

Button btn3 = new Button(“Three”);

 

// Create the spacer

Region spacer = new Region();

 

// Set the Vgrow for the spacer

VBox.setVgrow(spacer, Priority.ALWAYS);

 

// Create the VBox layout pane

VBox vbox = new VBox(10, btn1, spacer, btn2, btn3);

vbox.setPadding(new Insets(10));