Advanced Java Programming - Old Questions

7. Discuss grid layout with suitable example. (5)

5 marks | Asked in 2069

The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Components are placed in columns and rows.

Every Component in a GridLayout has the same width and height. Components are added to a GridLayout starting at the top-left cell of the grid and proceeding left to right until the row is full. Then the process continues left to right on the next row of the grid, and so on.

GridLayout Constructors:

GridLayout()

creates a grid layout with one column per component in a row.

GridLayout(int rows, int cols)

creates a grid layout with the given rows and columns but no gaps between the components.

GridLayout(int rows, int cols, int int hgap, int vgap)

creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps.

 

Example:

import java.awt.*;

import javax.swing.*;

public class GridDemo

{

      JButton b1, b2, b3, b4, b5, b6;

      GridDemo()

      {

           JFrame f = new JFrame("GridLayoutDemo");

           b1 = new JButton("A");

           b2 = new JButton("B");

           b3 = new JButton("C");

           b4 = new JButton("D");

           b5 = new JButton("E");

           b6 = new JButton("F");

           f.add(b1);

           f.add(b2);

           f.add(b3);

           f.add(b4);

           f.add(b5);

           f.add(b6);

           f.setLayout(new GridLayout(2, 3));

           f.setSize(200, 200);

           f.setVisible(true);

      }

      public static void main(String args[])

      {

           new GridDemo();

      }

}