Java


Java Tutorial


Admission Enquiry Form

  

Java GridLayout

Java GridLayout

The Grid Layout manager arranges components into grid of rows and columns.Components are added first to the top row of the grid, beginning with the leftmost grid cell and continuing to the right.
Grid layout is created with the GridLayout class.

Constructors of GridLayout class

Type of Constructor Constructor Description
GridLayout() It creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns) It creates a grid layout with the given rows and columns but no gaps between the components.
GridLayout(int rows, int cols, int hgap, int vgap) It creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps.

The int rows and cols arguments of the constructor sent for number of rows and number of columns in the grid.
The int hgap and vgap argument of the constructor give horizontal and vertical gap between the components in pixels.By default gap between components under grid layout is 0 pixel in both vertical and horizontal directions.




Example of GridLayout

import javax.swing.*;
import java.awt.*;

class DemoGridLayout extends JFrame
{
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9;
GridLayout grid;
DemoGridLayout()
{
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9);
grid=new GridLayout(3, 3, 5 , 5);
setLayout(grid);
setTitle("GridLayout Demo");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class GridLayoutEx
{
public static void main(String[] args)
{
DemoGridLayout demogrid=new DemoGridLayout();

}
}

Output

The code above will display :