GridLayout represents a layout manager with a specified number of rows and columns. Every rectangle cell has the same size and contains a component, which fills in the entire size of the cell.
In this example we are going to design a simple calculator using
GridLayout, where the grid will contains simple components.
1. Syntax of the Java GridLayout
GridLayout has two constructors:
GridLayout():empty constructor with one column and as many rows as the components.
GridLayout(int rows, int cols):a constructor with specified rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap):a constructor with specified rows, columns, horizontal and vertical gaps.
The arguments that are used are:
rows:is the number of rows in the grid.
cols:represents the number of columns in the grid.
hgap:is the horizontal space between the cells.
vgap:is the vertical space between the cells
2. Example of GridLayout
Before showing how to implement a
GridLayout, it is important to mention that we should initialize a
Jframe, which is the window that contains the components.
GridLayoutTest.java file and paste the following code.
Lets explain the code above. After we instantiate and set
Jframe, we create the
GridLayout by declaring its rows, columns and its horizontal and vertical gaps. After that we set the instantiated
GridLayout as the layout of our container by calling
setLayout() method. In order to include the components to our layout, we have to add them to the
JFrame and not to the
GridLayout. In our example we add some components (
JButton) directly to the frame and some others dynamically, as an array of that type (array of
The execution of this example is shown in the next image.
You can notice that the orientation of the components is horizontal and left-to-right, because that is the default value of the
3. Download the source code
This was an example of GridLayout in Java.
Download the source code of this example: Java GridLayout Example
Last updated on May 8th, 2020