JavaFX Layout GridPane Example

In this JavaFX source code example, we will see how to use the JavaFX GridPane layout with an example.

GridPane places its nodes into a grid of rows and columns. Nodes may span multiple rows or columns. GridPane is the most flexible built-in layout pane.

The setGridLinesVisible enables us to show the lines of the layout grid, which allows us to visually debug the layout.

JavaFX Layout GridPane Example

The layout of this example consists of a label, text field, list view, and two buttons.

package sample;

import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.stage.Stage;

public class Main extends Application {

    public void start(Stage stage) {


    private void initUI(Stage stage) {

        GridPane root = new GridPane();
        root.setPadding(new Insets(5));

        ColumnConstraints cons1 = new ColumnConstraints();

        ColumnConstraints cons2 = new ColumnConstraints();

        root.getColumnConstraints().addAll(cons1, cons2);

        RowConstraints rcons1 = new RowConstraints();

        RowConstraints rcons2 = new RowConstraints();

        root.getRowConstraints().addAll(rcons1, rcons2);

        Label lbl = new Label("Name:");
        TextField field = new TextField();
        ListView view = new ListView();
        Button okBtn = new Button("OK");
        Button closeBtn = new Button("Close");

        GridPane.setHalignment(okBtn, HPos.RIGHT);

        root.add(lbl, 0, 0);
        root.add(field, 1, 0, 3, 1);
        root.add(view, 0, 1, 4, 2);
        root.add(okBtn, 2, 3);
        root.add(closeBtn, 3, 3);

        Scene scene = new Scene(root, 280, 300);

        stage.setTitle("New folder");

    public static void main(String[] args) {