Page 739 - Introduction to Programming with Java: A Problem Solving Approach
P. 739
Adding Components
Assume that you’re inside a GridLayout container class. To add a component to one of the container’s cells, call the add method like this:
add(<component>);
Note the simplicity of the add method call. In particular, note that there’s no mention of the cell that the component plugs into. So how does the GridLayout manager know which cell to plug the component into? The GridLayout manager positions components within the container using left-to-right, top-to- bottom order. The first added component goes in the top-left-corner cell, the next added component goes in the cell to the right of the first component, and so on.
The code fragment below generates a two-row, three-column table with six buttons. The code fragment specifies gaps of 5 pixels between the rows and columns.
setLayout(new GridLayout(2, 3, 5, 5));
add(new JButton("1"));
add(new JButton("2"));
add(new JButton("3"));
add(new JButton("4"));
add(new JButton("5"));
add(new JButton("6"));
Assume the above code fragment is part of a complete, working program. Here’s what the program displays:
Apago PDF Enhancer
horizontal gap = 5 pixels
The six rectangles you see are the six cells, but they’re also the six buttons. The buttons are the same size as the cells because, with a GridLayout manager, components expand to fill their cells. That should sound familiar; BorderLayout components do the same thing.
Specifying Number of Rows and Number of Columns
When creating a GridLayout manager, you call the GridLayout constructor with a number-of-rows argument and a number-of-columns argument. Those two arguments require some explanation. To help with the explanation, consider three different cases.
Case one:
If you know the number of rows and columns in your table and the table will be completely filled in (i.e., there are no empty cells), call the GridLayout constructor with the actual number of rows and the
17.5 GridLayout Manager 705
v
lg
v
e
e
r
r
t
ti
i
c
ca
a
l
g
a
ap
p
=
=
5
5
p
p
i
i
x
x
e
e
l
l
s
s