BorderPane
BorderPane is a layout in JavaFX that divides the window into 5 areas:
- top
- bottom
- left
- right
- center
The center area takes all remaining space.
This layout is very common for application windows, especially if you want:
- a menu or toolbar at the top
- a sidebar on the left
- main content in the center
- status bar at the bottom
Example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BorderPaneExample extends Application {
@Override
public void start(Stage stage) {
BorderPane root = new BorderPane();
// Top
Label topLabel = new Label("Top Area");
root.setTop(topLabel);
// Left
Button leftButton = new Button("Left");
root.setLeft(leftButton);
// Center
Label centerLabel = new Label("Main Content");
root.setCenter(centerLabel);
// Right
Button rightButton = new Button("Right");
root.setRight(rightButton);
// Bottom
Label bottomLabel = new Label("Status Bar");
root.setBottom(bottomLabel);
Scene scene = new Scene(root, 500, 300);
stage.setTitle("BorderPane Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Visual structure:
+---------------------------+
| TOP |
+-----+-------------+-------+
|LEFT | CENTER | RIGHT |
| | | |
+-----+-------------+-------+
| BOTTOM |
+---------------------------+
Important methods:
root.setTop(node);
root.setBottom(node);
root.setLeft(node);
root.setRight(node);
root.setCenter(node);
Each area can contain only one node, but that node can itself be another layout like VBox, HBox, AnchorPane, or even another BorderPane.
Example with a sidebar and content:
VBox sidebar = new VBox(10);
sidebar.getChildren().addAll(
new Button("Home"),
new Button("Settings"),
new Button("About")
);
Label content = new Label("Welcome!");
BorderPane root = new BorderPane();
root.setLeft(sidebar);
root.setCenter(content);
FXML version:
<BorderPane xmlns:fx="http://javafx.com/fxml">
<top>
<Label text="Top Area"/>
</top>
<left>
<Button text="Left"/>
</left>
<center>
<Label text="Main Content"/>
</center>
<right>
<Button text="Right"/>
</right>
<bottom>
<Label text="Bottom Area"/>
</bottom>
</BorderPane>
You can also set margins around the areas:
BorderPane.setMargin(leftButton, new Insets(10));
That adds space around the node.
Since you want to work on a JavaFX app with a sidebar and main content area, BorderPane is probably one of the best layouts for your UI:
- sidebar →
setLeft(...) - top toolbar →
setTop(...) - main page content →
setCenter(...) - footer/status →
setBottom(...)