FlowPane
FlowPane is a layout container that places elements in a row or column, and when there is no more space, it automatically wraps them to the next line.
It works somewhat like text wrapping in a paragraph.
Example with horizontal flow:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class FlowPaneExample extends Application {
@Override
public void start(Stage stage) {
FlowPane flowPane = new FlowPane();
flowPane.setHgap(10); // horizontal space between items
flowPane.setVgap(10); // vertical space between rows
for (int i = 1; i <= 10; i++) {
flowPane.getChildren().add(new Button("Button " + i));
}
Scene scene = new Scene(flowPane, 300, 150);
stage.setTitle("FlowPane Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
If the window is wide enough, the buttons appear on one row:
Button1 Button2 Button3 Button4 Button5 ...
If you make the window narrower, they automatically move to the next line:
Button1 Button2 Button3
Button4 Button5 Button6
Button7 Button8 ...
Important properties:
flowPane.setHgap(10); // space between items horizontally
flowPane.setVgap(10); // space between rows
flowPane.setPrefWrapLength(200); // preferred width before wrapping
Example with wrap length:
FlowPane flowPane = new FlowPane();
flowPane.setPrefWrapLength(200);
That tells JavaFX to start a new row when the width becomes around 200 pixels.
You can also make it vertical:
FlowPane flowPane = new FlowPane(Orientation.VERTICAL);
Then items go downward first, and when there is no more height, they wrap into another column.
Example:
FlowPane verticalPane = new FlowPane(Orientation.VERTICAL);
for (int i = 1; i <= 8; i++) {
verticalPane.getChildren().add(new Button("Item " + i));
}
FXML version:
<FlowPane hgap="10" vgap="10" prefWrapLength="250"
xmlns:fx="http://javafx.com/fxml">
<children>
<Button text="One"/>
<Button text="Two"/>
<Button text="Three"/>
<Button text="Four"/>
</children>
</FlowPane>
Typical uses:
- a toolbar with many buttons
- image thumbnails
- tags or chips
- lists of categories
- responsive layouts
For example, if your JavaFX app has many monitor action buttons or wallpaper thumbnails, FlowPane is often better than HBox, because it wraps automatically instead of pushing everything off-screen.
Difference between HBox and FlowPane:
| HBox | FlowPane |
|---|---|
| Keeps everything on one row | Wraps items to new rows |
| No automatic wrapping | Automatic wrapping |
| Good for a small fixed number of controls | Good for many controls |