How to use the BorderPane JavaFX
JavaFX BorderPane divides its layout area into five regions. BorderPane JavaFX is the most used root node for a scene because BorderPane satisfies all the layout requirements for a typical Windows-based application. The five useful regions are the top, right, bottom, left, and center. A screen uses five regions to place its content in a typical Windows application. For example:
- At the top, it should be a menu or a toolbar.
- At the bottom, it should be a status bar.
- On the left, it should be a navigation panel.
- On the right, it should be additional information
- and the main content in the center.
BorderPane in JavaFX is the best layout as a root node. For example, if you create an application, this layout is perfect if you want your program to be more user-responsive.
How to create the JavaFX BorderPane
Creating the JavaFX BorderPane is very easy. It has similar functionalities to other layouts in JavaFX. The BorderPane class provides constructors to create BorderPane objects with or without children or nodes.
// Create an empty borderpane BorderPane bPane = new BorderPane(); // Create a BorderPane with a node Button button = new Button("Button"); BorderPane bPane2 = new BorderPane(button); // Create a BorderPane with nodes in each of the five regions Button centerButton = new Button("Center"); Button topButton = new Button("Top"); Button rightButton = new Button("Right"); Button bottomButton = new Button("Bottom"); Button leftButton = new Button("Left"); BorderPane bPane3 = new BorderPane(centerButton, topButton, rightButton, bottomButton, leftButton);
Setting constraints for children in JavaFX BorderPane
JavaFX BorderPane allows you to set individual children’s alignment and margin constraints. The alignment for a child node is defined relative to its region. The following lists will be the default alignment in every layout region.
- Pos.TOP_LEFT for Top
- Pos.BOTTOM_LEFT for Bottom
- Pos.TOP_LEFT for left
- Pos.TOP_RIGHT for right
- Pos.CENTER for center
Use the setAlignment(Node child, Pos value) static method of the BorderPane to set the children’s or nodes’ alignment. Proceed to the example given below to learn more about how it works.
BorderPane borderPane = new BorderPane(); Button topButton = new Button("Button"); borderPane.setTop(topButton); BorderPane.setAlignment(topButton, Pos.TOP_RIGHT);
Use the setMargin(Node child, Insets value) static method of the BorderPane to set the margin for the children or node.
BorderPane.setMargin(topButton, new Insets(10));
Leave a Reply