Constructing a GridLayout
When you create an instance of GridLayout , you normally will
specify the number of rows and columns that you want it to provide, and you
may choose to specify the amount of horizontal and vertical space that
should appear between adjacent components. However, you can choose to set
any of these values after construction using the setRows() ,
setColumns() , setHgap() , and
setVgap() methods. An example of creating a
GridLayout and assigning it to a container is shown in the
code below. This application parses the command line parameters to
determine how many rows and columns should be available, creates 20
JButton instances, and adds each button to the container:
import java.awt.*;
import javax.swing.*;
public class GridTest extends JFrame {
public static void main(String[] args) {
if (args.length 2) {
System.out.println("You must enter a row count and a column count");
return;
}
int rows = Integer.parseInt(args[0]);
int cols = Integer.parseInt(args[1]);
GridTest gt = new GridTest(rows, cols);
gt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gt.pack();
gt.setVisible(true);
}
public GridTest(int rows, int cols) {
Container pane = getContentPane();
pane.setLayout(new GridLayout(rows, cols));
for (int i = 0; i 20; i++) {
JButton button = new JButton(Integer.toString(i + 1));
pane.add(button);
}
}
}
When you create a GridLayout , you can specify a value of 0
for either the row or column count, but not both. If you set the number of
rows to 0, GridLayout creates as many
rows as it needs to display all the components using the specified number
of columns. For example, the screenshot below illustrates what will be
displayed when 0 is specified for the number of rows and 3 for the number
of columns:
Similarly, if you set the number of columns to 0, the layout manager
creates as many columns as it needs to display the child components using
the specified number of rows. In the next screenshot, the row count was set
to 3 and the column count to 0:
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.