AWT Grid Layout Manager Explained

1. Introduction to Grid Layout

In Java, we can arrange the controls in rows and columns using Grid Layout Manager. For example in the calculator, the buttons are formed in grids. We can easily achieve this through Grid Layout Manager. Each controls in the grid holds same space. In other words, all the controls in this Layout have same dimensions. The Layout Manager arranges the controls Left to Right and then Top to Bottom. Below picture shows how the layout manager organized controls in rows and columns. The number shows the order in which the layout manager placed the control in the container.

Controls In AWT Grid Layout
Controls In AWT Grid Layout

In this example, we use the Frame Window as the container. To know more about the Frame Window read the article here: Hub Pages.

2. Frame Window Setup

The GridLayout class is available in the java.awt package. So first we need to import this class. Below is the code which imports other classes required for this example:

Next, we set title to our frame window. The application’s main function will pass this title. After this, we set size and location to the frame window. Below is the code:

After deciding the size and location, we register our frame window to the WindowListener. This will help us close the frame through X button on the upper right corner. Below is the code:

3. Create Thirty Buttons on the Grid Layout Container

In Grid Layout we will place thirty button controls. So first we need to create java.awt.Buttons  and add that to the container. In our example, the Frame Window acts as a container. Below is the code which adds thirty Buttons to the Frame Window.

GridLayoutclass in java is a component manager which arranges the controls in rows and columns. These rows and columns forms a grid and the manager places one control in each grid. Note, the manager provides same size for each grid. In the below code, we create 3×10 grid. In other words, we create three rows and ten columns of the grid. Then we assign this layout to our frame window. Remember, we added thirty buttons to the frame window through a for loop.

Below is the output of executing this Example.

Output of the example
Output of the example


Categories: AWT, Java

Tags: ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: