Tech and Media Labs
This site uses cookies to improve the user experience.




JavaFX VBox

Jakob Jenkov
Last update: 2016-05-14

The JavaFX VBox component is a layout component which positions all its child nodes (components) in a vertical row. The Java VBox component is represented by the class javafx.scene.layout.VBox .

Creating a VBox

You create an VBox using its constructor like this:

VBox vbox = new VBox();

VBox also has a constructor which takes a variable length list of components it should layout. Here is an example of how to do that:

Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button Number 2");

VBox vbox = new VBox(button1, button2);

This VBox example will layout the two Button instances under each other in a vertical row.

Adding a VBox to the Scene Graph

For an VBox to be visible it must be added to the scene graph. This means adding it to a Scene object, or as child of a layout which is attached to a Scene object.

Here is an example that attaches a JavaFX VBox with the two Button instances to the scene graph:

package com.jenkov.javafx.layouts;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


public class VBoxExperiments extends Application  {


    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("HBox Experiment 1");

        Button button1 = new Button("Button Number 1");
        Button button2 = new Button("Button Number 2");

        VBox vbox = new VBox(button1, button2);

        Scene scene = new Scene(vbox, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

The result of running the above JavaFX VBox example is an application that looks like this:

A JavaFX VBox component displayed in the scene graph.

Space Between Nodes

In the earlier example the VBox positioned the nodes (button controls) right under the other. You can make the VBox insert some space between its nested controls by providing the space in the VBox constructor. Here is an example of setting the space between nested controls in an VBox:

VBox vbox = new VBox(20, button1, button2);

This example sets the spacing between the controls in the VBox layout component to 20.

You can also set the space between the nested controls using the setSpacing() method, like this:

vbox.setSpacing(50);

This example will set the spacing between nested controls to 50.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC