FreeCode

Donate HTML/CSS JavaFX Java Home
JavaFX Starter Template JavaFX Labels JavaFX Buttons JavaFX Toggle Buttons JavaFX Radio Buttons and Toggle Groups JavaFX Checkboxes JavaFX Choice Boxes JavaFX Combo Boxes JavaFX Text Areas JavaFX Text Fields JavaFX List Views JavaFX Image Views JavaFX Color Pickers JavaFX Date Pickers JavaFX Resizable Split Pane Layouts JavaFX VBox (Vertical Box Layouts) JavaFX HBox (Horizontal Box Layouts) JavaFX Flow Pane Layouts JavaFX Tile Pane Layouts JavaFX Web Views

JavaFX HBox (Horizontal Box Layouts)

Code Description:

The code provided below shows how to create a basic horizontal layout using JavaFX.

HBox Syntax:

HBox hBox = new HBox();

Runnable JavaFX HBox Example Code:

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

public class Demo extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
		
	int spacingAmount = 5;
		
	HBox root = new HBox(spacingAmount);

	Button button1 = new Button("Button1");
	Button button2 = new Button("Button2");
	Button button3 = new Button("Button3");
	Button button4 = new Button("Button4");

	root.getChildren().addAll(button1, button2, button3, button4);
			
	primaryStage.setTitle("HBox Demo");
	primaryStage.setScene(new Scene(root, 200, 200));
	primaryStage.show();
		
    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Note: You will NOT be able to copy and paste this code into your IDE unless you first set up JavaFX for your project. Check out this link if you need help setting up JavaFX:

JavaFX Comprehensive Setup Guide

Output:

JavaFX HBox Layout Output Image

Important Methods:

  • getChildren().addAll() - Used to add child elements or layouts to the hbox.
  • setSpacing() - Sets the horizontal spacing between each of the hbox child elements.
  • setStyle() - Set an inline CSS-like style on the vbox. EX: "hBox.setStyle("-fx-background-color: green;");"
  • setAlignment() - Set how the child elements are aligned in the hbox. EX: "hBox.setAlignment(Pos.CENTER);"

Related Links:

JavaFX Resizable Split Pane Layouts JavaFX VBox (Vertical Box Layouts) JavaFX Flow Pane Layouts JavaFX Tile Pane Layouts