# How to create a grid pane using JavaFX?

JavaFXObject Oriented ProgrammingProgramming

Once you create all the required nodes for your application you can arrange them using a layout. Where a layout is a process of calculating the position of objects in the given space. JavaFX provides various layouts in the javafx.scene.layout package.

## Grid Pane

In this layout, you can arrange the nodes as a grid of rows and columns. You can create a grid pane in your application by instantiating the javafx.scene.layout.GridPane class.

You can set a nodes position in the pane using the setRowIndex() and setColumnIndex() methods.

This class has the following properties −

• alignment −(Pos) specifies the position of the grid within the dimensions of the panes.

• gridLinesVisible − (boolean) specifies whether to show the lines highlighting the panes rows and columns.

• hgap − (double) specifies the horizontal gap between the columns of the grid.

• vgap − (double) specifies the vertical gap between the rows of the grid.

You can customize the appearance of the grid by setting values to these properties using their respective setter methods.

To add nodes to this pane you can either pass them as arguments of the constructor or, add them to the observable list of the pane as −

getChildren().addAll();

## Example

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class GridLayoutExample extends Application {
public void start(Stage stage) {
//Creating labels
Text text1 = new Text("Email");
TextField textField1 = new TextField();
//Creating Buttons
Button button1 = new Button("Submit");
Button button2 = new Button("Clear");
//Creating a Grid Pane
GridPane gridPane = new GridPane();
//Setting size for the pane
gridPane.setMinSize(400, 200);
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
//Setting the Grid alignment
gridPane.setAlignment(Pos.CENTER);
//Arranging all the nodes in the grid
//Setting the stage
Scene scene = new Scene(gridPane, 595, 200, Color.BEIGE);
stage.setTitle("Grid Layout");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}

## Output

Updated on 19-May-2020 13:06:24