Java Reference
In-Depth Information
12.18.3 GridLayout
The GridLayout layout manager divides the container into a grid so that components can
be placed in rows and columns . Class GridLayout inherits directly from class Object and
implements interface LayoutManager . Every Component in a GridLayout has the same
width and height. Components are added to a GridLayout starting at the top-left cell of
the grid and proceeding left to right until the row is full. Then the process continues left
to right on the next row of the grid, and so on. The application of Figs. 12.43-12.44 dem-
onstrates the GridLayout layout manager by using six JButton s.
1
// Fig. 12.43: GridLayoutFrame.java
2
// GridLayout containing six buttons.
3
import java.awt.GridLayout;
4
import java.awt.Container;
5
import java.awt.event.ActionListener;
6
import java.awt.event.ActionEvent;
7
import javax.swing.JFrame;
8
import javax.swing.JButton;
9
10
public class GridLayoutFrame extends JFrame implements ActionListener
11
{
12
private final JButton[] buttons; // array of buttons
13
private static final String[] names =
14
{ "one" , "two" , "three" , "four" , "five" , "six" };
15
private boolean toggle = true ; // toggle between two layouts
16
private final Container container; // frame container
17
private final GridLayout gridLayout1; // first gridlayout
private final GridLayout gridLayout2; // second gridlayout
18
19
20
// no-argument constructor
21
public GridLayoutFrame()
22
{
23
super ( "GridLayout Demo" );
24
gridLayout1 = new GridLayout( 2 , 3 , 5 , 5 ); // 2 by 3; gaps of 5
gridLayout2 = new GridLayout( 3 , 2 ); // 3 by 2; no gaps
25
26
container = getContentPane();
27
setLayout(gridLayout1);
28
buttons = new JButton[names.length];
29
30
for ( int count = 0 ; count < names.length; count++)
31
{
32
buttons[count] = new JButton(names[count]);
33
buttons[count].addActionListener( this ); // register listener
34
add(buttons[count]); // add button to JFrame
35
}
36
}
37
38
// handle button events by toggling between layouts
39
@Override
40
public void actionPerformed(ActionEvent event)
41
{
Fig. 12.43 | GridLayout containing six buttons. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search