Way2Java

Java AWT GridLayout Manager

After knowing the importance of layout managers, FlowLayout and BorderLayout, let us study the other layout manager – GridLayout.

As the name indicates the container is divided into a grid of cells dictated by rows and columns. Each cell accommodates one component. Like with FlowLayout, in GridLayout also, the position need not be mentioned. But remember, in BorderLayout, position is to be mentioned. As the rows and columns are fixed, components addition goes one after another automatically. Following is an example of GridLayout of 3 rows and 4 columns (12 cells).

Following are the properties of GridLayout.

  1. The grid layout size (no. of cells) is given by rows and columns.
  2. The default gap between the components is 0 pixels which can be changed explicitly.
  3. Components should be added continuously. It is not possible to avoid some cells addition in the middle, and add to later cells.

Following program illustrates the use of GridLayout.

import java.awt.*;
public class GLDemo extends Frame
{
  public GLDemo()
  {
    setLayout(new GridLayout(3, 4));
    setBackground(Color.red);
                        // create 12 anonymous button objects and add them
    for(int i = 0; i < 12; i++)
    {
      add(new Button("OK " + i));
    } 
    
    setSize(350, 300);
    setVisible(true);
  }                  
  public static void main(String args[])
  {
    new GLDemo();
  }
}

setLayout(new GridLayout(3, 4));
setBackground(Color.red);

The frame is divided into 3 rows and 4 columns comprising of 12 cells. In each cell, one button is added. The background color red is not seen as the default gap between the components is 0 pixels. The following statement gives the gap.

setLayout(new GridLayout(3, 4, 10, 20));

The extra last two parameters 10 and 20 indicates horizontal gap and vertical gap. As in the previous statement, 3 and 4 indicate rows and columns. Now the background color red is seen. Horizontal gap means the gap between the components of a row. Vertical gap means the gap between the components of two rows.

The knowledge of FlowLayout and BorderLayout is very essential for layout management. It is required to know about Panels also to get the desired layout of components.

The frame you get do not close when clicked over the close icon on the title bar of the frame. It requires extra code close icon to work.