Site iconJava PDF Blog

An Introduction to JavaFX Panes with Code Examples

As a developer at IDR Solutions I spend a lot of my time working with JavaFX and Panes in our combined Swing and JavaFX PDF Viewer. I thought it might be useful to introduce you to the JavaFX Panes with simple code example.

There are 6 Panels in javaFX such as: BorderPane, StackPane, GridPane, FlowPane,TilePane and AnchorPane.

StackPane

Stack pane allows you to place many nodes one on top of an other.

StackPane root = new StackPane();
Button btn1 = new Button(" 1 ");
Button btn2 = new Button("22222222");
root.getChildren().addAll(btn2, btn1);
root.setStyle("-fx-background-color: #87CEFA;");

GridPane

GridPane allows you to create a flexible grid of rows and columns and position each node in exact place.

 GridPane grid = new GridPane();
grid.setPadding(new Insets(10, 10, 10, 10));
grid.setMinSize(300, 300);
grid.setVgap(5);
grid.setHgap(5);

Text username = new Text("Username:");
grid.add(username, 0, 0);

TextField text = new TextField();
text.setPrefColumnCount(10);
grid.add(text, 1, 0);

Text password = new Text("Password:");
grid.add(password, 0, 1);

TextField text2 = new TextField();
text2.setPrefColumnCount(10);
grid.add(text2, 1, 1);
grid.setStyle("-fx-background-color: #D8BFD8;");

FlowPane

Flow Pane lays all nodes one after an other in the order they were added.

 FlowPane flow = new FlowPane();
flow.setPadding(new Insets(10, 10, 10, 10));
flow.setStyle("-fx-background-color: DAE6F3;");
flow.setHgap(5);
flow.getChildren().addAll(left, center);

TilePane

TilePane is similar to the flow pane. All nodes are placed in a grid in the same order they were added.

 TilePane tile = new TilePane();
tile.setPadding(new Insets(10, 10, 10, 10));
tile.setPrefColumns(2);
tile.setStyle("-fx-background-color: #CD5C5C;");
HBox hbox2 = new HBox(8); // spacing = 8
hbox2.getChildren().addAll(top, left, center);
tile.getChildren().add(hbox2);

AnchorPane

AnchorPane allows you to position nodes in the top, bottom, left side, right side, or center of the pane.

 AnchorPane anchorpane = new AnchorPane();
Button buttonSave = new Button("Save");
Button buttonCancel = new Button("Cancel");
anchorpane.setStyle("-fx-background-color: #A9A9A9;");
HBox hb = new HBox();
hb.getChildren().addAll(buttonSave, buttonCancel);
anchorpane.getChildren().addAll(hb);
anchorpane.setMinSize(300, 100);
AnchorPane.setRightAnchor(hb, 10.0);

BorderPane

BorderPane splits the scene in five regions such as: top, bottom, left, right, and center. Where you can adjust added nodes. BorderPane also allows you to add different panes in each region as shown in my example. However  you cannot use the same pane more than once.

 BorderPane pane = new BorderPane();
pane.setLeft(anchorpane);
pane.setCenter(root);
pane.setRight(grid);
pane.setTop(flow);
pane.setBottom(tile);

Scene scene = new Scene(pane, 300, 250);

Hopefully you found this guide useful.