Java Reference
In-Depth Information
42
if (toggle) // set layout based on toggle
43
container.setLayout(gridLayout2);
44
else
45
container.setLayout(gridLayout1);
46
47
toggle = !toggle;
48
container.validate(); // re-lay out container
49
}
50
} // end class GridLayoutFrame
Fig. 12.43 | GridLayout containing six buttons. (Part 2 of 2.)
1
// Fig. 12.44: GridLayoutDemo.java
2
// Testing GridLayoutFrame.
3
import javax.swing.JFrame;
4
5
public class GridLayoutDemo
6
{
7
public static void main(String[] args)
8
{
9
GridLayoutFrame gridLayoutFrame = new GridLayoutFrame();
10
gridLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11
gridLayoutFrame.setSize( 300 , 200 );
12
gridLayoutFrame.setVisible( true );
13
}
14
} // end class GridLayoutDemo
Fig. 12.44 | Testing GridLayoutFrame .
Lines 24-25 (Fig. 12.43) create two GridLayout objects. The GridLayout con-
structor used at line 24 specifies a GridLayout with 2 rows, 3 columns, 5 pixels of hori-
zontal-gap space between Component s in the grid and 5 pixels of vertical-gap space between
Component s in the grid. The GridLayout constructor used at line 25 specifies a GridLayout
with 3 rows and 2 columns that uses the default gap space (1 pixel).
The JButton objects in this example initially are arranged using gridLayout1 (set for
the content pane at line 27 with method setLayout ). The first component is added to the
first column of the first row. The next component is added to the second column of the
first row, and so on. When a JButton is pressed, method actionPerformed (lines 39-49)
is called. Every call to actionPerformed toggles the layout between gridLayout2 and
gridLayout1 , using boolean variable toggle to determine the next layout to set.
Line 48 shows another way to reformat a container for which the layout has changed.
Container method validate recomputes the container's layout based on the current
layout manager for the Container and the current set of displayed GUI components.
 
Search WWH ::




Custom Search