Java Reference
In-Depth Information
public GridLayout(int rows, int cols, int hgap, int vgap). Creates a new
GridLayout with the specified number of rows and columns and also
with the specified horizontal and vertical gap.
public GridLayout().
Creates a GridLayout object with one row and any
number of columns.
One (but not both) of the values for rows and columns can be zero. If the
value of columns is 0, the grid will have the specified number of rows, but any
number of columns. Similarly, if the value of rows is 0, the grid will have the
specified number of columns, but any number of rows.
For example, suppose that we instantiate a GridLayout manager with three
columns and 0 rows:
GridLayout grid = new GridLayout(0, 3);
If 10 components are added to a container with grid as its layout manager,
the components will be displayed in four rows and three columns, with the
last row containing only one component.
The no-argument constructor of GridLayout creates a GridLayout with one
row and an indeterminate number of columns. This is equivalent to the
following statement:
new GridLayout(1,0);
The following GridLayoutDemo program creates a JPanel, assigns its con-
tent pane to have GridLayout, and six JButton components are added to the
content pane. Study the program and see whether you can determine what the
JFrame will look like. In particular, try to determine the layout of the six but-
tons relative to the order they are added to the JFrame. The output is shown in
Figure 12.8.
import java.awt.*;
import javax.swing.*;
public class GridLayoutDemo extends JFrame
{
private JButton [] buttons;
public GridLayoutDemo(String title)
{
super(title);
Container contentPane = this.getContentPane();
contentPane.setLayout(new GridLayout(2,3,10,15));
buttons = new JButton[6];
for(int i = 0; i < buttons.length; i++)
{
Search WWH ::




Custom Search