JavaFX: Putting StackPane in HBox

This entry is part 12 of 55 in the series JavaFX

We know that HBox is a region in BorderPane and we could understand that BorderPane is flat and it is divided into a few regions as shown below.


StackPane provides a z-order for us to put our elements and in a way, the elements are leveled with one above the other.

We can put a StackPane on a HBox by creating an addStackPane method and pass the Hbox object into the StackPane to have the StackPane added to the HBox.

In the example below, I have:


The purpose of the above line is to add the StackPane into the HBox and not the other way round.

In our method implementation in line 41, we have:

private void addStackPane(HBox hb)

This is to bring in the hb, which is an instance of HBox in to the method.

The actual line that attaches the StackPane into the HBox is:

StackPane in HBox
package javafxapplication11;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class JavaFXApplication11 extends Application {

    public void start(Stage stage) {

        BorderPane border = new BorderPane();

        border.setPrefSize(500, 400);

        HBox hbox = addHorizontalBox();



        Scene scene = new Scene(border);
        stage.setTitle("Layout Example");;

    private void addStackPane(HBox hb) {

        StackPane stack = new StackPane();
        Rectangle xIcon = new Rectangle(35.0, 35.0);

        Text xText = new Text("X");
        xText.setFont(Font.font("Verdana", FontWeight.BOLD, 18));

        stack.getChildren().addAll(xIcon, xText);

        StackPane.setMargin(xText, new Insets(0, 10, 0, 0));

        HBox.setHgrow(stack, Priority.ALWAYS);


    private HBox addHorizontalBox() {

        HBox hbox = new HBox();
        hbox.setPadding(new Insets(15, 12, 15, 12));
        hbox.setSpacing(10);   // Gap between nodes
        hbox.setStyle("-fx-background-color: blue;");

        Button buttonAccept = new Button("Accept");
        buttonAccept.setPrefSize(100, 20);

        Button buttonNext = new Button("Next");
        buttonNext.setPrefSize(100, 20);

        hbox.getChildren().addAll(buttonAccept, buttonNext);

        return hbox;

    public static void main(String[] args) {




Series Navigation<< JavaFX: Making the previous example simpler
JavaFX: Absolute Positioning Using Pane >>