Previous | Next | Trail Map | Creating a User Interface | Laying Out Components within a Container


How to Use GridLayout

Here's an applet that shows a GridLayout in action.


Your browser can't run 1.0 Java applets, so here's a picture of the window the program brings up:


As the above applet shows, a GridLayout places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If you resize the GridLayout window, you'll see that the GridLayout changes the cell size so that the cells are as large as possible, given the space available to the container.

Below is the code that creates the GridLayout and the components it manages. (Here's the whole program. The program runs either within an applet, with the help of AppletButton, or as an application.)

setLayout(new GridLayout(0,2));
setFont(new Font("Helvetica", Font.PLAIN, 14));
   
add(new Button("Button 1"));
add(new Button("2"));
add(new Button("Button 3"));
add(new Button("Long-Named Button 4"));
add(new Button("Button 5"));
The constructor tells the GridLayout class to create an instance that has two columns and as many rows as necessary. It's one of two constructors for GridLayout. Here are the declarations for both constructors:
public GridLayout(int rows, int columns)
public GridLayout(int rows, int columns,
		  int horizontalGap, int verticalGap)
At least one of the rows and columns arguments must be non-zero. The horizontalGap and verticalGap arguments to the second constructor allow you to specify the number of pixels between cells. If you don't specify gaps, their values default to zero. (In the applet above, the apparent gaps are the result of the Buttons reserving extra space around their apparent display area [CHECK].)


Previous | Next | Trail Map | Creating a User Interface | Laying Out Components within a Container