JavaFX HBox Example

In this tutorial, we will learn how to use the JavaFX HBox layout in the JavaFX application.

JavaFX HBox

The JavaFX HBox component is a layout component that positions all its child nodes (components) in a horizontal row. 

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.

Complete JavaFX tutorial at https://www.javaguides.net/p/javafx-tutorial.html.

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.

A 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

Related JavaFX Examples

Comments