HBox
HBox is a layout container that arranges its children horizontally, from left to right.
It is useful when you want buttons, labels, text fields, or other controls on the same row.
Example:
import javafx.application.Application;
import javafx.geometry.Insets;
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) {
Button saveButton = new Button("Save");
Button cancelButton = new Button("Cancel");
Button helpButton = new Button("Help");
HBox hbox = new HBox();
// Space between children
hbox.setSpacing(10);
// Space around the whole HBox
hbox.setPadding(new Insets(15));
hbox.getChildren().addAll(saveButton, cancelButton, helpButton);
Scene scene = new Scene(hbox, 300, 100);
stage.setTitle("HBox Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Result:
[Save] [Cancel] [Help]
Important properties:
hbox.setSpacing(10); // space between children
hbox.setPadding(new Insets(15)); // space around the box
You can also align the children:
hbox.setAlignment(Pos.CENTER);
Example:
HBox hbox = new HBox(10); // 10 = spacing
hbox.setAlignment(Pos.CENTER);
hbox.getChildren().addAll(
new Button("Yes"),
new Button("No")
);
Now the buttons appear centered.
Common alignments:
Pos.CENTER
Pos.CENTER_LEFT
Pos.CENTER_RIGHT
Pos.TOP_LEFT
Pos.BOTTOM_RIGHT
You can make one child grow to fill extra space:
TextField searchField = new TextField();
Button searchButton = new Button("Search");
HBox hbox = new HBox(10, searchField, searchButton);
// Let the TextField take remaining width
HBox.setHgrow(searchField, Priority.ALWAYS);
This is very useful in toolbars:
[____________________] [Search]
The TextField expands when the window gets wider.
FXML version:
<HBox spacing="10"
alignment="CENTER_LEFT"
xmlns:fx="http://javafx.com/fxml">
<children>
<Button text="Save"/>
<Button text="Cancel"/>
<Button text="Help"/>
</children>
</HBox>
Example with growing text field in FXML:
<HBox spacing="10" xmlns:fx="http://javafx.com/fxml">
<children>
<TextField HBox.hgrow="ALWAYS"/>
<Button text="Search"/>
</children>
</HBox>
Typical uses:
- toolbar
- row of buttons
- label + text field on the same line
- search bar
- navigation buttons
Difference between HBox and FlowPane:
| HBox | FlowPane |
|---|---|
| Keeps everything on one line | Wraps to next line if needed |
| Good for a fixed row | Good for many items |