The GridLayout Class Used in AWT
The GridLayout class represents a second type of layout manager. A GridLayout puts components within a grid with a specified number of rows and columns. All components within the grid are of equal size.
Creating a GridLayout is similar to creating a FlowLayout, except that it has different constructor methods. The default constructor creates a layout including a single component per column. The other two are listed below:
GridLayout (int rows, int cols);
GridLayout (int rows, int cols, int hgap, int vgap);
Use of these constructors should be self-explanatory. If you don’t specify the gaps their values will default to zero. If you give either the rows or columns value as zero, or you add more than rows x columns components, the layout manager will adjust its values so that the components still fit within the grid.
The following listing, GridTest, creates a 3 x 3 arrangement of labels. There is a five-pixel horizontal and vertical gap between the labels. Each label background color is green so you can see the gaps.
import java.applet.*;
import java.awt.*;
public class GridTest extends Applet
{
public void init()
{
// create a String and a StringTokenizer to parse the String
String string = "My Head Is My Only House Unless It Rains";
java.util.StringTokenizer st = new java.util.StringTokenizer(string);
// create a 3 by 3 grid layout with a 5 pixel gap between components
setLayout(new GridLayout(3, 3, 5, 5));
// for each String token, create a label with a green background and
// add it to the panel
while(st.hasMoreTokens())
{
Label label = new Label(st.nextToken(), Label.CENTER);
label.setBackground(Color.green);
add(label);
}
}
} // GridTest