Java Grids
Volume Number: 12
Issue Number: 11
Column Tag: Getting Started
Two Java Grid Layouts 
By Dave Mark
Note: Source code files accompanying article are located on MacTech CD-ROM orsource code disks.
Last month, we introduced the Java Layout Manager and saw the power of layouts
combined with panels. This month, we’ll look at two important layout classes,
GridLayout and GridBagLayout, and present a series of applets that bring these two
classes to life.
There is a newly reformatted set of Java API documentation, collectively known
as the 1.0.2 API. If you don’t already have this, go get it now. The URL is:
http://java.sun.com/doc/api_documentation.html
There are two Mac download links on this page. Though it’s bigger, you might try
the .hqx file (as opposed to the .bin file). I’m not sure why, but when I downloaded the
.bin file and dropped it on StuffIt Expander, the final .sea file was corrupted. On the
other hand, by the time you read this, the problem most likely will have been
corrected.
GridLayout
As its name implies, the GridLayout lays out its components in a grid. GridLayout
has two constructors:
public GridLayout( int rows, int cols );
This one creates a grid layout with the specified rows and columns. As you’ll see,
GridLayout does the best it can to lay the current set of components out in this
configuration. But what if you have too few components? Or too many? This month’s
sample applets are ideal for experimenting.
The second constructor adds two new parameters:
public GridLayout( int rows, int cols,
int hgap, int vgap );
This version creates a grid layout with the specified rows and columns, but also
lets you specify a minimal horizontal and vertical gap to appear between the
components.
GridLayout is pretty straightforward. Here’s a sample applet to take it for a spin.
• Launch the CodeWarrior IDE and create a new “Java Applet” project called
GridLayout.µ.
• Create a new source code window, type in the following source code, save as
GridLayout.Java, and add to it the project.
import java.awt.*;
public class MyGrid extends java.applet.Applet
setLayout( new GridLayout( 4, 4 ) );
add( new Button( “1” ) );
add( new Button( “2” ) );
add( new Button( “3” ) );
add( new Button( “4” ) );
add( new Button( “5” ) );
add( new Button( “6” ) );
add( new Button( “7” ) );
add( new Button( “8” ) );
add( new Button( “9” ) );
add( new Button( “10” ) );
add( new Button( “11” ) );
add( new Button( “12” ) );
add( new Button( “13” ) );
add( new Button( “14” ) );
add( new Button( “15” ) );
add( new Button( “16” ) );
}
}