GridLayout Example
The layout manager GridLayout lays out a container's components in a rectangular grid.The container is divided into equal-sized rectangles, and one component is placed in each rectangle.
This GridLayou example lays out labels and buttons in five rows of two columns.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// GridLayout Example
import java.awt.*;
import javax.swing.*;
class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.setLayout(new GridLayout(5,0));
for(int i=0;i<5;++i) {
cp.add(new JLabel("label "+i,JLabel.CENTER));
cp.add(new JButton("button "+i));
}
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
11 The two parameters of the GridLayout constructor are the number of rows and columns needed for the grid.
When a parameter is zero it means that either the rows or columns, as appropriate, can be any number.
