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




JavaFX HBox

Jakob Jenkov
Last update: 2016-05-14

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

Creating a HBox

You create an HBox using its constructor like this:

HBox hbox = new HBox();

HBox 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");

HBox hbox = new HBox(button1, button2);

This HBox example will layout the two Button instances next to each other in a horizontal row.

Adding a HBox to the Scene Graph

For an HBox 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 HBox 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.HBox;
import javafx.stage.Stage;

public class HBoxExperiments 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");

        HBox hbox = new HBox(button1, button2);

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

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

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

A JavaFX HBox component displayed in the scene graph.

Notice that the two Button controls are kept on the same horizontal row even if there is not enough space to show them in their fully preferred widths. The buttons do not "wrap" down on the next line.

Space Between Nodes

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

HBox hbox = new HBox(20, button1, button2);

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

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

hbox.setSpacing(50);

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

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC