JavaFX Layout HBox Example

In this JavaFX source code example, we will see how to use the HBox layout pane with an example.

HBox lays out its children in a single horizontal row. If the HBox has a border and/or padding set, then the contents will be layed out within those insets.

The HBox layout is represented by javafx.scene.layout.HBox class. 

We just need to instantiate the HBox class in order to create an HBox layout.

JavaFX HBox Example

The example shows six buttons in a single row. The row is right-aligned. There is some space between the buttons:
package com.javafx.examples.layout;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class HBoxExample extends Application {

    @Override
    public void start(Stage stage) {

        initUI(stage);
    }

    private void initUI(Stage stage) {

        HBox root = new HBox(5);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.BASELINE_RIGHT);

        Button prevBtn = new Button("Previous");
        Button nextBtn = new Button("Next");
        Button cancBtn = new Button("Cancel");
        Button helpBtn = new Button("Help");
        Button exitBtn = new Button("Exit");
        Button stopBtn = new Button("Stop");

        root.getChildren().addAll(prevBtn, nextBtn, cancBtn, helpBtn, exitBtn, stopBtn);

        Scene scene = new Scene(root);
        stage.setTitle("Row of buttons");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Let's understand the above JavaFX program.

HBox pane is created with some spacing:

 HBox root = new HBox(5);

We create some padding around the HBox:

root.setPadding(new Insets(10));

The setAlignment() method aligns the nodes to the right:

root.setAlignment(Pos.BASELINE_RIGHT);

The buttons are added to the container:

root.getChildren().addAll(prevBtn, nextBtn, cancBtn, helpBtn, exitBtn, stopBtn);

We created six buttons:

        Button prevBtn = new Button("Previous");
        Button nextBtn = new Button("Next");
        Button cancBtn = new Button("Cancel");
        Button helpBtn = new Button("Help");
        Button exitBtn = new Button("Exit");
        Button stopBtn = new Button("Stop");

Output


Comments