Learn how to use the JavaFX layout. Studying and working with layout in JavaFX is easy, and layout in JavaFX is essential in your JavaFX application. Managing all of your nodes in the scene graph is challenging if your application lacks layout panes. Is it difficult to have water without a container? Layout panes in your JavaFX application play a significant role in making it more user-experience friendly. Also, as a developer, you can quickly and easily develop your application. In addition, to make your application look more engaging to the users, you can add JavaFX CSS.
In this article, I will demonstrate everything and provide examples. You will learn how to use the layouts in JavaFX. I will explain the different types of layouts panes in JavaFX, such as HBox, VBox, BorderPane, etc. Also, their uses, adding nodes and showing you how each of them works in JavaFX. Open your IDE, follow along with the examples, and get started.
What is layout in JavaFX
A layout pane in JavaFX is to arrange nodes in a scene graph. There are two types of layouts to arrange nodes, A static and dynamic layout.
The static layout is not ideal for a responsive application because the nodes will stay the same at their position if the user resizes the window. The user interface looks good if the window is not resizable. In comparison, the dynamic layout is perfect for applications that are designed to be responsive.
Both static and dynamic layouts have advantages and disadvantages. Suppose you are working on the fixed layout or static layout. In that case, it gives you full control, which means that you can freely create the design of the user interface without hassle. Still, the only disadvantage of it is not a responsive layout. Since the dynamic layout is responsive, the disadvantage of this layout is time-consuming. The dynamic layout requires more programming work to achieve your desired layout. You can also use the Scene Builder to make your job easier.
Working with layout in JavaFX
There are various container classes in JavaFX. Working with layout in JavaFX is simple and easy. These container classes help us create our Java application look more user-friendly. In these container classes, we will learn the basics of the JavaFX layout. We will learn how we can make the layouts, add nodes to our layout and customize each property of our layout in JavaFX. The following container classes will explain their descriptions.
Layouts in JavaFX
These are the container classes in JavaFX. Please read each of them to get an idea of how they work.
- Group – A group is also powerful. It applies effects, transformations to all its children nodes.
- Pane – This layout is used for the absolute positioning of its children.
- HBox – This layout is used to arrange the node or its children horizontally.
- VBox – This layout is used to arrange the node or its children vertically.
- FlowPane – This layout is similar functionalities of the HBox and the VBox. It can arrange its children horizontally or vertically if nodes do not fit in a single row or column.
- BorderPane – This layout is the most used layout in JavaFX. It divides its layout area into regions.
- StackPane – From the word stack, it arranges its children in a back-to-front stack.
- TilePane – The TilePane arranges its children in a grid of uniformly sized cells.
- GridPane – The GridPane arranges its children in a grid of variable-sized cells.
- AnchorPane – The AnchorPane arranges its children by anchoring their edges to the edge of the layout.
- TextFlow – The TextFlow is designed to display rich-text
JavaFX Layout Examples
Now, we learned and understood each of the layouts in JavaFX. Let’s go through each layout and learn more about making the layout, adding nodes inside the layout, and look at the given examples below and get started.
How to use the Group JavaFX Layout
Group has a feature of a container, it has its layout policy, coordinate system, and it is a subclass of a parent class. Group is best reflected by calling it a collection of nodes rather than a container because the Group is used to manipulate a collection of nodes. You can control all nodes in your JavaFX application once the nodes are inside the Group. If you have nodes inside the Group, you can apply effects, transformations, and other properties applied to a Group. The used properties to a Group will reflect it in all nodes in the Group.
Since the Group does its layout policy and when you add nodes in the Group, all nodes or children are positioned at 0,0 axis by default. You must manually write the code to place all nodes inside the Group. We can use LayoutX and LayoutY to set them easily.
Creating the Group
There are options to create the Group object. We can use the no-args constructor to create an empty group. Group obj = new Group();
It is what a no-args constructor looks like. We can also use the var-args constructor to create the Group. For example: Group obj = new Group(btn1, btn2);
. We created the Group with two Buttons inside the Group using the var-args constructor in making the Group.
Adding children to a Group
A container is meant to contain children or nodes. Since the Group has a feature of a container, we can add children to it. We can add children when creating the object or after creating the object. Using the getChildren() method, we can add children to the container. See the example code below.
// adding the nodes using the no-args constructor Group obj = new Group(); obj.getChildren().addAll(btn1, btn2); // or add them one by one obj.getChildren().add(btn1); obj.getChildren().add(btn2); // adding the nodes using the var-args constructor Group obj = new Group(btn1, btn2);
If you run that piece of code, your nodes will overlap because we haven’t set the position of the nodes. Set the LayoutX and LayoutY to place them in your desired position.
Example
In this example, we learn to set the position of the nodes and add effects and transformation to see what that looks like using the Group layout.
import java.io.IOException; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.effect.DropShadow; import javafx.stage.Stage; /** * * @author KENSOFT */ public class JavaFXLayout extends Application { @Override public void start(Stage stage) throws IOException { Button btn1 = new Button("Button 1"); Button btn2 = new Button("Button 2"); btn1.setLayoutX(10); btn1.setLayoutY(10); btn2.setLayoutX(200); btn2.setLayoutY(10); Group root = new Group(); root.getChildren().addAll(btn1, btn2); root.setEffect(new DropShadow()); root.setRotate(5); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Group"); stage.show(); } public static void main(String[] args) { launch(args); } }
Output
How to use the Pane in JavaFX
When Absolute positioning is needed, you may use a Pane in JavaFX. By default, it placed the nodes at the 0,0 axis, and you need to set the position of the nodes manually. The Pane resizes all resizable children to their preferred sizes. When you have a node in the Pane, it will set its preferred size to the same as the node. You can also tell the Pane to compute its preferred size based on its children.
The following example will show you how to create the Pane, add nodes in the Pane, set the position of the nodes, and use the computed size of the Pane based on the children’s sizes. Proceed to the example below to see what that looks like.
Example
import java.io.IOException; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.stage.Stage; /** * * @author KENSOFT */ public class JavaFXLayout extends Application { @Override public void start(Stage stage) throws IOException { Button btn1 = new Button("Button 1"); Button btn2 = new Button("Button 2"); btn1.relocate(10, 10); btn2.relocate(100, 10); Pane root = new Pane(); root.getChildren().addAll(btn1, btn2); root.setStyle("-fx-border-style: solid inside;" + "-fx-border-width: 5;" + "-fx-border-color: red;"); // Added a border to see the difference with computed size root.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Pane"); stage.show(); } public static void main(String[] args) { launch(args); } }
Output
How to use the HBox in JavaFX
JavaFX HBox arranges its children in a horizontal row style, which means that if you are going to add the HBox to your JavaFX application and add nodes in the HBox. HBox automatically lays out its children in a single horizontal row design. This layout helps you create your design easily if you want your nodes to be arranged nicely in a horizontal row.
When you add nodes inside the HBox, you cannot set the node’s location in an HBox because the HBox automatically computes them. Still, you can control the location manually by customizing the properties of the HBox and setting constraints on the children.
Creating the JavaFX HBox
To create the JavaFX Hbox, we need to make the HBox object using the HBox constructor. We can create the HBox objects with or without setting the spacing and the initial set of children. The following example below will show you how to create an empty HBox, create the HBox with spacing, and create the HBox with spacing and initial children. Take a look at the given code below.
// Creates an empty HBox HBox obj1 = new HBox(); // Creates an HBox with spacing of 15px HBox obj2 = new HBox(15); // Creates an HBox with spacing and initial children Button btn1 = new Button("Button 1"); Button btn2 = new Button("Button 2"); HBox obj3 = new HBox(15, btn1, btn2);
There are some HBox properties that you should be aware of. The following three HBox properties are listed below.
- alignment – The alignment property helps you align the nodes inside the HBox layout area. The fillHeight property is ignored if the vertical alignment is set to BASELINE.
- fillHeight – This property is used to specify the resizable children to fill the full height of the HBox. Please know that this property is ignored if the vertical alignment is set to BASELINE.
- spacing – This property is used to specify the spacing of the children. The default value is set to 0.
Now, let us go over each of the properties and show you examples of each. Let’s start with:
Alignment Property
The Alignment property is effortless to use, and it is used to specify how the nodes are aligned within the content area of the HBox. HBox allocates just enough space for its content to layout all children at their preferred size. The Alignment property has several geometry positions, like BASELINE_CENTER, BASELINE_LEFT, BASELINE_RIGHT, BOTTOM_CENTER, BOTTOM_LEFT, BOTTOM_RIGHT, CENTER, CENTER_LEFT, CENTER_RIGHT, TOP_CENTER, TOP_LEFT, and TOP_RIGHT. You may notice the effect of the alignment property if the HBox is bigger than its preferred size. The following example will show how the alignment property is used in the JavaFX program.
// Setting the alignment of the children root.setAlignment(Pos.BOTTOM_CENTER);
Output
FillHeight Property
The FillHeight property specifies the resizable node to fill the full height of the content area of the HBox. Note that this property only affects nodes that allow for vertical expansion. For example, if you have a button inside your HBox and the maximum height of the button is based on its preferred height, this doesn’t expand the button if you will use the fillHeight property. To expand the button, you need to set its maximum height to Double.MAX_VALUE. If you don’t want to fill the children’s height or nodes, you can disable it by setting the fillHeight property to false. The following example will show how the fillHeight property is used.
HBox root = new HBox(10); root.setPrefSize(600, 400); Button btn1 = new Button("Button 1"); btn1.setMaxHeight(Double.MAX_VALUE); CheckBox chkBox = new CheckBox("Check me to Fill"); chkBox.setSelected(true); // Setting the FillHeight chkBox.setOnAction(event ->{ root.setFillHeight(chkBox.isSelected()); }); root.setStyle("-fx-padding: 10;"); root.getChildren().addAll(chkBox, btn1); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Understanding HBox"); stage.show();
Output
Spacing Property
This property is also straightforward to use. The Spacing property specifies the horizontal distance between the nodes in an HBox. The default value of the spacing is set to 0px. To set the spacing, you can set it using the setSpacing() method or in constructors. To apply the spacing between the children of the HBox, It should be like this. root.setSpacing(10);
. If you don’t want to use the setSpacing() method, you may also use the constructor like HBox root = new HBox(10);
There is another feature in HBox. You can let the nodes or children grow horizontally by using the setHgrow() method. The hgrow constraints specify whether a node expands horizontally when additional space is available. The HBox class provides setHgrow() and setMargin() method to specify these constraints. The following code is an example of setting the Hgrow method, HBox.setHgrow(textField, Priority.ALWAYS);
if you want to add margins, do this. HBox.setMargin(textField, new Insets(10,2,10,2));
. The first 10 in the Insets parameter is for top margin 10px, 2px for right, 10px for bottom, 2px for left.
YouTube Video
How to use the VBox in JavaFX
The JavaFX VBox is also very easy to use because it is similar to the HBox. The VBox layout its children in a single vertical column while the HBox layout its children in a horizontal style. So, if you are creating an application that places the nodes in column style or vertical style, you will need to use the VBox to place them perfectly.
Like HBox, you cannot set the locations for your nodes or children. The VBox automatically computes them and puts them in the right place. You can still control the location by settings the constraints but about it later and let’s move on creating the VBox in JavaFX.
Creating the JavaFX VBox
Working with VBox is very similar to working with an HBox. The difference are they work in opposite directions. To create the JavaFX VBox, we need to make the VBox object using the VBox constructor. We can create the VBox objects with or without setting the spacing and the initial set of children. The following example below will show you how to create an empty VBox, create the VBox with spacing, and create the VBox with spacing and initial children. Take a look at the given code below.
// Creates an empty VBox VBox obj1 = new VBox(); // Creates a VBox with spacing of 15px VBox obj2 = new VBox(15); // Creates a VBox with spacing and initial children Button btn1 = new Button("Button 1"); Button btn2 = new Button("Button 2"); VBox obj3 = new VBox(15, btn1, btn2);
There are some VBox properties that you should be aware of. The following three VBox properties are listed below.
- alignment – The alignment property helps you align the nodes inside the VBox layout area.
- fillWidth – This property is used to specify the resizable children to fill the full width of the VBox.
- spacing – This property is used to specify the spacing of the children. The default value is set to 0.
Now, let us go over each of the properties and show you examples of each. Let’s start with:
Alignment Property
The Alignment property is effortless to use, and it is used to specify how the nodes are aligned within the content area of the VBox. VBox allocates just enough space for its content to layout all children at their preferred size. The Alignment property has several geometry positions, like BASELINE_CENTER, BASELINE_LEFT, BASELINE_RIGHT, BOTTOM_CENTER, BOTTOM_LEFT, BOTTOM_RIGHT, CENTER, CENTER_LEFT, CENTER_RIGHT, TOP_CENTER, TOP_LEFT, and TOP_RIGHT. You may notice the effect of the alignment property if the VBox is bigger than its preferred size. The following example will show how the alignment property is used in the JavaFX program.
// Set the alignment vbox.setAlignment(Pos.BOTTOM_RIGHT);
FillWidth Property
The FillWidth property specifies the resizable node to fill the full widthof the content area of the VBox. Note that this property only affects nodes that allow for horizontal expansion. For example, if you have a button inside your VBox and the maximum width of the button is based on its preferred width, this doesn’t expand the button if you will use the fillWidth property. To expand the button, you need to set its maximum width to Double.MAX_VALUE. If you don’t want to fill the children’s width or nodes, you can disable it by setting the fillHeight property to false. The following example will show how the fillHeight property is used.
VBox root = new VBox(15); Button b1 = new Button("One"); Button b2 = new Button("Two"); Button b3 = new Button("Three"); // Set the max width of the buttons to Double.MAX_VALUE // so they can grow horizontally b1.setMaxWidth(Double.MAX_VALUE); b2.setMaxWidth(Double.MAX_VALUE); b3.setMaxWidth(Double.MAX_VALUE); root.setStyle("-fx-padding: 10;"); root.getChildren().addAll(b1, b2, b3); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Understanding VBox"); stage.show();
Spacing Property
This property is also straightforward to use. The Spacing property specifies the vertical distance between the nodes in an VBox. The default value of the spacing is set to 0px. To set the spacing, you can set it using the setSpacing() method or in constructors. To apply the spacing between the children of the VBox, It should be like this. vbox.setSpacing(10);
. If you don’t want to use the setSpacing() method, you may also use the constructor like VBox vbox = new VBox(10);
There is another feature in VBox. You can let the nodes or children grow vertically by using the setVgrow() method. The Vgrow constraints specify whether a node expands vertically when additional space is available. The VBox class provides setVgrow() and setMargin() method to specify these constraints. The following code is an example of setting the Vgrow method, VBox.setVgrow(textArea, Priority.ALWAYS);
if you want to add margins, do this. VBox.setMargin(textArea, new Insets(5));
.
YouTube Video
How to use the JavaFX FlowPane
FlowPane in JavaFX is a very simple layout pane that lays out its children in rows and columns. The JavaFX FlowPane is something like a combination of HBox and VBox, so if you have a FlowPane layout in your application. “Flow Pane,” the name itself, lets the nodes flow horizontally or vertically. JavaFX FlowPane is used in situations where the content is necessary to display.
For example, you have a series of buttons horizontally or vertically. When the user resizes the window that doesn’t have a FlowPane layout, If the window is too small, the contents will not be displayed. Using the FlowPane helps the layout to display the content as possible. If the window becomes smaller and smaller, the children inside the JavaFX FlowPane will flow horizontally or vertically. FlowPane in JavaFX may be arranged left to right or right to left, controlled by the nodeOrientation property.
Creating the FlowPane in JavaFX
Creating the FlowPane in JavaFX is very easy. FlowPane provides several ways to make the FlowPane layout. You can create an empty FlowPane. You can also specify the orientation, spacing, and adding and initial nodes in the FlowPane. Now, let’s go over the example code given below and learn how to make the FlowPane layout in JavaFX.
// Create an empty FlowPane FlowPane flowPane1 = new FlowPane(); // Create an empty FlowPane and set the orientation FlowPane flowPane2 = new FlowPane(Orientation.VERTICAL); // Create an empty FlowPane with 5px horizontal and 10px vertical spacing FlowPane flowPane3 = new FlowPane(5, 10); // Create an empty FlowPane with orientation and spacing FlowPane flowPane4 = new FlowPane(Orientation.VERTICAL, 5, 10); // Create a FlowPane with initial nodes inside FlowPane flowPane5 = new FlowPane(new Button("Button 1"), new Button("Button 2"));
FlowPane has properties you need to learn. These properties are helpful when you are using the FlowPane Layout. Take time to read the descriptions of each property. These are the alignment, rowValignment, columnHalignment, hgap, vgap, orientation, prefWrapLength. Please proceed below.
- alignment – The alignment property is to align the FlowPane, and the default value is Pos.TOP_LEFT.
- rowValignment – This property specifies the vertical alignment of the nodes within each row in a horizontal FlowPane.
- columnHalignment – This property specifies the horizontal alignment of the nodes within each column in a vertical FlowPane.
- hgap and vgap – The hgap and vgap properties specify the nodes’ horizontal and vertical gaps.
- orientation – The orientation property specifies the orientation of the FlowPane.
- prefWrapLength – The preferred width in a horizontal FlowPane and the preferred height in a vertical FlowPane where the content should wrap and the default value is 400.
Alignment Property
The alignment property of the JavaFX FlowPane controls the alignment of its content. You need to set the parameter of the setAlignment() method, and the default value is Pos.TOP_LEFT. The Pos value contains a vertical alignment and horizontal alignment. In a horizontal FlowPane, each row is aligned using the hpos value of the alignment, and rows (the entire content) are aligned using the vpos value. In a vertical FlowPane, each column is aligned using the vpos value of the alignment, and the columns (the entire content) are aligned using the hpos value. Proceed to the example given below.
// Create an empty FlowPane FlowPane root = new FlowPane(); // Setting the alignment to center right root.setAlignment(Pos.CENTER_RIGHT); Button b1 = new Button("One"); Button b2 = new Button("Two"); Button b3 = new Button("Three"); root.getChildren().addAll(b1, b2, b3); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Understanding FlowPane"); stage.show();
Output
rowValignment and columnHalignment Properties
JavaFX FlowPane layouts its children at their preferred sizes. Rows and Columns could be of different sizes but you can align the nodes or children in each row or column using the rowValignment and columnHalignment properties.
In a horizontal JavaFX FlowPane, the nodes in one row may be of different heights. The row’s height is the largest of the preferred heights of all nodes in the row. The rowValignment property lets you specify the vertical alignment of the nodes in each row. While in a vertical JavaFX FlowPane, the nodes in one column may be of different widths. The column’s width is the largest of the preferred widths of all nodes in the column. The columnHalignment property lets you specify the horizontal alignment of children in each column. Proceed to the example given below.
public void start(Stage stage) { FlowPane f1 = createFlowPane(HORIZONTAL, VPos.TOP, HPos.LEFT); FlowPane f2 = createFlowPane(HORIZONTAL, VPos.CENTER, HPos.LEFT); FlowPane f3 = createFlowPane(VERTICAL, VPos.CENTER, HPos.RIGHT); HBox root = new HBox(f1, f2, f3); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Understanding FlowPane"); stage.show(); } private FlowPane createFlowPane(Orientation orientation, VPos rowAlign, HPos colAlign){ Text text = new Text(); if(orientation == Orientation.HORIZONTAL){ text.setText(rowAlign.toString()); }else{ text.setText(colAlign.toString()); } TextArea textArea = new TextArea(orientation.toString()); textArea.setPrefColumnCount(5); textArea.setPrefRowCount(3); FlowPane flowPane = new FlowPane(orientation, 5, 10); flowPane.setRowValignment(rowAlign); flowPane.setColumnHalignment(colAlign); flowPane.setPrefSize(175, 130); flowPane.getChildren().addAll(text, textArea); flowPane.setStyle("-fx-padding: 10; -fx-border-style: solid inside; -fx-border-width: 2; -fx-border-insets: 5; -fx-border-radius: 5; -fx-border-color: red;"); return flowPane; }
Output
hgap and vgap Properties
The hgap and vgap in the JavaFX FlowPane are very easy to use. Using these properties will help you set gaps in between the nodes. Using the hgap property, the horizontal spacing between the nodes of children in a row. The vgap property specifies the spacing between the nodes or children in a column. Proceed to the example given below to learn how the hgap and vgap work.
// create a FlowPane with 5px hgap and 10px vgap FlowPane flowPane = new FlowPane(5, 10); // or setting the gap using the method flowPane.setHgap(15); flowPane.setVgap(10);
Orientation Property
The orientation property lets you set the orientation of FlowPane. To set the orientation of the FlowPane, you can set it to Orientation.HORIZONTAL
. You can also set the orientation using the setter method. Proceed to the example given below.
// create a horizontal FlowPane FlowPane flowPane = new FlowPane(Orientation.HORIZONTAL); // setting the FlowPane's orientation using the setter method flowPane.setOrientation(Orientation.HORIZONTAL);
prefWrapLength Property
The prefWrapLength property is the preferred width in a horizontal FlowPane or the preferred height in a vertical FlowPane where content should wrap. The prefWrapLength property is used to compute the preferred size of the FlowPane. Treat the value of this property as a hint to resize your FlowPane.
YouTube Video
How to use the JavaFX BorderPane
JavaFX BorderPane divides its layout area into five regions. BorderPane in JavaFX is the most used root node for a scene because the 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 the 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 BorderPane in JavaFX
Creating the JavaFX BorderPane is very easy. It is similar functionalities to other layouts in JavaFX. 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));
YouTube Video
How to use the JavaFX StackPane
StackPane in JavaFX lays out its children in a stack of nodes. From the word “stack” when adding nodes to a StackPane layout, the added nodes will stack or in pile form. StackPane is a powerful layout. It can overlay nodes. When creating an application, you can use the StackPane to overlay nodes if you are creative.
The preferred width of a StackPane is based on the widest child node, and the preferred height is based on the tallest child node. A StackPane resizes its resizable children to fill its content area, provided their maximum size allows them to expand beyond their preferred size.
Creating objects of the StackPane in JavaFX
You can create the StackPane layout with or without nods or children. StackPane class provides constructors to create the objects.
// Create an empty StackPane StackPane stackPane = new StackPane(); // Create a StackPane with nodes StackPane stackPane2 = new StackPane(RectangleBuilder.create().width(200).height(50).fill(Color.LAVENDER).build(), new Text("A rectangle"));
You can use the getChildren() method to add nodes to the StackPane. Adding nodes in a specific order is important to achieve your desired output. Nodes are drawn in the order they exist in the list. The following example below does not have the same result, and you need to be aware that if you are working with the StackPane.
// Overlay a text on a rectangle stackPane.getChildren().addAll(rect, text); // Overlay a rectangle on a text stackPane.getChildren().addAll(text, rect);
StackPane Properties
The StackPane has an alignment property. The alignment property is used to align the children within the content area of the StackPane. The default value is set to Pos.CENTER means that all children or nodes are aligned in the center of the content area of the StackPane. To set the alignment property, proceed to the example given below.
// set the StackPane alignment stackPane.setAlignment(Pos.TOP_LEFT);
YouTube Video
How to use the JavaFX TilePane
JavaFX TilePane lays out its children in a grid of uniformly sized cells. TilePane in JavaFX works similarly to FlowPanes. The differences are the heights and widths. Tiles in the TilePane are all in the exact sizes. The default width and height of all tiles in a TilePane are the width of the widest node or children and the height of the tallest node or children.
The TilePane also has an orientation. You can set the orientation based on your needs. You can set TilePane’s orientation to horizontal or vertical, and the default orientation of the TilePane is horizontal.
Creating the TilePane in JavaFX
Creating the TilePane’s object is very easy. TilePane provides constructors to create the TilePane object. You can create an empty TilePane, or with initial nodes inside, with spacing, or by defining the orientation. Please proceed to the example given below to learn more.
// Create an empty TilePane TilePane tilePane = new TilePane(); // Create an empty Vertical TilePane TilePane tilePane2 = new TilePane(Orientation.VERTICAL); // Create an empty horizontal TilePane with spacing 5px horizontal and 10px vertical spacing TilePane tilePane3 = new TilePane(5, 10); // Create a TilePane with nodes TilePane = new TilePane(new Button("Button 1"), new Button("Button 2"));
Adding nodes to a TilePane is still the same as other layouts. You can use the getChildren() method to add nodes or child nodes in a TilePane. tilePane.getChildren().addAll(button1, button2);
.
TilePane Properties
TilePane has properties, and you should know about these important properties. Please proceed below and learn more about these properties.
Alignment Property
This property is used to align the content of the TilePane, and the default alignment is Pos.TOP_LEFT. The alignment property will help you align if you want your content will align in that place. The example code given below will show you how to set the alignment in a TilePane.
TilePane tilePane = new TilePane(); tilePane.setAlignment(Pos.CENTER);
There is also a tileAlignment Property, the use of tileAlignment property is to align the child nodes within their tiles.
TilePane tilePane = new TilePane(); tilePane.setTileAlignemnt(Pos.TOP_LEFT);
hgap and vgap Properties
hgap and vgap is essential, setting gaps to make your nodes more beautiful for users. The hgap and vgap are spacing between columns and rows, the default value is 0. You can set the gaps in the constructors or using the setters something like setHgap(Double hg) method. The example code given below will show you how to set the gap in a Tilepane.
TilePane tilePane = new TilePane(); tilePane.setHgap(10); tilePane.setVgap(10);
Orientation Property
You can change the orientation if you don’t like the default orientation, which is Orientation.HORIZONTAL. If you set the orientation to vertical, the content flows in columns. Otherwise, the content flows in rows if you choose the horizontal orientation. You can use the constructors or the setter method to set the orientation. The example code given below will show you how to set the orientation in a TilePane.
TilePane tilePane = new TilePane(Orientation.VERTICAL); // or tilePane.setOrientation(Orientation.VERTICAL);
TileWidth and Tile height properties
The TilePane computes the widest and the tallest node or child node inside the TilePane to set the preferred size of its tiles. You may also use the prefTileWidth and prefTileHeight properties to manually modify the tiles’ size. The default size of the TilePane is set to Region.USE_COMPUTED_SIZE. The example code given below will show you how to set the preferred size of the tiles.
TilePane tilePane = new TilePane(); tilePane.setPrefTileWidth(40); tilePane.setPrefTileHeight(40); // You can also use the computed size: setPrefSize(Double prefWidth, Double prefHeight); tilePane.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
YouTube Video
How to use the GridPane in JavaFX
GridPane in JavaFX is also a bit complex to learn, but it is one of the most powerful layout panes in JavaFX. JavaFX GridPane lays out the child nodes or nodes in a dynamic grid of cells arranged in rows and columns. When you work with the GridPane layout, it will automatically generate the grid based on the number of nodes or child nodes you add to the GridPane, which is why GridPane is dynamic and powerful.
It should be noted that the GridPane indexes for columns and rows start at 0. Cells in the same row are all the same height, while cells in other rows may be of different heights, and cells in the same columns are all the same width, while cells in other columns may be of different widths. A row is tall enough to accommodate the tallest child node by default, while a column is wide enough to accommodate the widest child node. You can still change the size of the row and column, and GridPane allows us to modify the vertical and horizontal spacing.
Creating the JavaFX GridPane
The JavaFX GridPane is simple to create. Simply use the no-args constructor to create an empty GridPane with 0px spacing between rows and columns. Please proceed to the example code given below to learn more about how to create the GridPane.
GridPane gridPane = new GridPane();
After we’ve created an empty GridPane, the following step is to insert it with nodes. Adding nodes to our layout is similar to adding nodes to other layout panes. The getChildren() method is used to add nodes inside the GridPane. You can also use the convenience method to add nodes in the GridPane.
Button btn1 = new Button("Button 1"); Button btn2 = new Button("Button 2"); Button btn3 = new Button("Button 3"); GridPane root = new GridPane(); root.getChildren().addAll(btn1, btn2, btn3); // Using the convenience method to add nodes root.add(new Button("Button"), 0, 0); // (column 0, row 0) root.add(new Button("Button 2"), 0, 1); // (column 0, row 1) // or root.addRow(0, btn1); root.addRow(1, btn2); root.addColumn(0, btn3); root.addColumn(1, new Button("Button 4"));
Gridlines are important for debugging the GridPane, and you can display them by using the setGridLinesVisible(Boolean) method. The gridlines are mostly used for troubleshooting. When you wish to see the positions of your nodes in the grid, use the gridline.
Setting positions of the child nodes
If you use the getChildren() method to add nodes to the JavaFX GridPane, you must specify their positions using the GridPane class’s three static methods. You can modify the column and row indexes. Please see the sample code provided below to understand more about positioning your child nodes.
Button btn1 = new Button("Button 1"); Button btn2 = new Button("Button 2"); Button btn3 = new Button("Button 3"); GridPane root = new GridPane(); root.getChildren().addAll(btn1, btn2, btn3); // settings the positions // you can use this method GridPane.setColumnIndex(btn1, 0); GridPane.setColumnIndex(btn2, 1); GridPane.setRowIndex(btn3, 1); // or using the constraints GridPane.setConstraints(btn1, 0, 0); // (column 0, row 0) GridPane.setConstraints(btn2, 1, 0); // (column 1, row 0) GridPane.setConstraints(btn3, 0, 1); // the output is the same
You may also set the columnIndex, rowIndex, columnSpan, rowSpan, and so on using the setConstraints() method. Please see the description below to learn more about it.
- columnIndex – The column index indicates where in the layout area the child nodes start.
- rowIndex – The row index indicates where in the layout area the child nodes start.
- columnSpan – The column span is the number of columns in the layout area of a child node span. The default is 1.
- rowSpan – The row span is the number of rows in the layout area of a child node span. The default is 1.
- hAlignment – This type of constraint provides the horizontal alignment of the child node.
- vAlignment – This type of constraint provides the vertical alignment of the child node.
- hgrow – This type of constraint will help you grow the node horizontally when the user resizes the window.
- vgrow – This type of constraint will help you grow the node vertically when the user resizes the window.
- margin – The margin constraint will specify the margin space of the child node.
YouTube Video
How to use the JavaFX AnchorPane
The JavaFX AnchorPane is similar to pinning an object to the board. The pinned object will be stretched if you resize the board. The AnchorPane arranges its children by anchoring its four edges to its own four edges at a set distance. The AnchoPane may be used for two things: aligning the children or node along with one or more of the AnchorPane’s edges, and stretching the children or node when the AnchorPane is resized.
The AnchorPane in JavaFX has four anchor constraints. These are the topAnchor, rightAnchor, bottomAnchor, and leftAnchor. When you anchor a child node to the edges of an AnchorPane, the child node will stretch to maintain the set anchor distance while the AnchorPane is resized.
Creating the AnchorPane in JavaFX
You can create an empty AnchorPane using the no-args constructor. Something like this AnchorPane root = new AnchorPane();
you can also insert an initial nodes AnchorPane root = new AnchorPane(btn1, btn2);
.
It is also simple to add nodes to the AnchorPane using the getChildren() method. Keep in mind that by default, the nodes are positioned on the 0, 0 axis. Set the anchor constraints for the node to anchor them to one more edge of the AnchorPane at a set distance. The preferred size of the AnchorPane is based on the preferred size of the node.
Setting the constraints
Setting constraints is the most practical way to make your AnchorPane look more user-friendly. The following list below will explain to you the four anchor constraints.
- topAnchor – The topAnchor will help you set the distance between the top edge of the AnchorPane layout and the child node.
- rightAnchor – The rightAnchor will help you set the distance between the right edge of the AnchorPane layout and the child node.
- bottomAnchor – The bottomAnchor will help you set the distance between the bottom edge of the AnchorPane layout and the child node.
- leftAnchor – The leftAnchor will help you set the distance between the left edge of the AcnhorPane layout and the child node.
Please see the example code below.
// Setting the anchor constraints Button btn1 = new Button("Button 1"); AnchorPane root = new AnchorPane(btn1); AnchorPane.setTopAnchor(btn1, 10.0); AnchorPane.setBottomAnchor(btn1, 10.0);
It is important to note that the parameter next to the child node in the anchor constraints is Double; if you just input 10, an error is generated since it is determined as an integer.
YouTube Video
How to use the JavaFX TextFlow
The JavaFX TextFlow is a layout pane for displaying rich text. What exactly do you mean by “rich text”? Rich text is made up of several text nodes. TextFlow combines the text in all Text nodes into a single text flow. To create a new paragraph in a text flow, a new line character ( \n ) is used to start a new paragraph. The text you input is wrapped at the width of the layout.
This layout is very similar to a FlowPane, resizing the window with this layout leads the text to flow like a FlowPane. The great thing about this layout is that you can add any other nodes to it, such as Buttons, TextFields, and so on. Let’s get started on creating the TextFlow object.
Creating the JavaFX TextFlow
You can use the no-args constructor to create an object, and you can also pass a list of nodes when you create it.
// Create an empty TextFlow TextFlow textFlow = new TextFlow(); // or Pass a list of nodes in the constructor Text text1 = new Text("This is cool!"); Text text2 = new Text("Learning with kensoftph.com"); TextFlow textFlow = new TextFlow(text1, text2); // or add nodes using the getChildren() textFlow.getChildren().addAll(text1, text2);
TextFlow Properties
This layout also features properties that you may modify, such as lineSpacing and textAlignment, which you can use to customize its layout.
- lineSpacing – This property is used to change the vertical spacing between lines. The default value is 0px.
- textAlignment – This property is used to change the alignment of the TextFlow. The value you can use are the LEFT, RIGHT, CENTER, and JUSTIFY. The default value is LEFT.
To use these properties, proceed to the example code below.
textFlow.setTextAlignment(TextAlignment.CENTER); textFlow.setLineSpacing(5);
I hope you got a lot out of this post. Share this to teach others how to use JavaFX layouts.