TilePane and HBox
Here’s a clear breakdown of the difference between TilePane and HBox in JavaFX:
| Feature | HBox | TilePane |
|---|---|---|
| Layout Direction | Horizontal only (left to right). | Can be horizontal or vertical; wraps automatically. |
| Child Wrapping | No wrapping; all children stay on the same row. | Yes, tiles wrap to the next row/column when space runs out. |
| Spacing Control | setSpacing() → space between children. |
setHgap() and setVgap() → horizontal & vertical gaps. |
| Size of Children | Children maintain their preferred sizes unless HBox.setHgrow() is used. |
Tiles are arranged uniformly; each tile can resize automatically to fill space. |
| Use Case | Toolbars, single row of buttons, horizontal layouts. | Dashboards, photo galleries, icon grids, multiple rows/columns. |
| Orientation | Always horizontal. | Horizontal or vertical (Orientation.HORIZONTAL / Orientation.VERTICAL). |
Example to Compare
HBox Example
HBox hbox = new HBox(10); // spacing = 10
hbox.getChildren().addAll(
new Button("A"),
new Button("B"),
new Button("C"),
new Button("D")
);
- Always one row:
A B C D - Won’t wrap if the window is small → buttons may get cut off
TilePane Example
TilePane tilePane = new TilePane();
tilePane.setHgap(10);
tilePane.setVgap(10);
tilePane.setPrefColumns(2); // max 2 tiles per row
for (int i = 1; i <= 4; i++) {
tilePane.getChildren().add(new Button("Tile " + i));
}
- Wraps automatically into multiple rows:
Tile 1 Tile 2
Tile 3 Tile 4
✅ Rule of thumb:
- Use HBox for a single horizontal row where wrapping is not needed.
- Use TilePane when you need a grid-like layout that wraps automatically, like dashboards, galleries, or monitor/wallpaper previews.