Java Reference
In-Depth Information
If both the number of rows and the number of columns are nonzero, the number of
rows is the dominating parameter; that is, the number of rows is fixed, and the layout
manager dynamically calculates the number of columns. For example, if you specify
three rows and three columns for a grid that has ten components, GridLayout creates
three fixed rows of four columns, with the last row containing two components.
Listing 12.4 gives a program that demonstrates grid layout. The program is similar to the one
in Listing 12.3, except that it adds three labels and three text fields to the frame of
GridLayout instead of FlowLayout , as shown in Figure 12.7.
F IGURE 12.7 The GridLayout manager divides the container into grids; then the compo-
nents are added to fill in the cells row by row.
L ISTING 12.4 ShowGridLayout.java
1
import javax.swing.JLabel;
2
import javax.swing.JTextField;
3
import javax.swing.JFrame;
4
import java.awt.GridLayout;
5
6 public class ShowGridLayout extends JFrame {
7 public ShowGridLayout() {
8 // Set GridLayout, 3 rows, 2 columns, and gaps 5 between
9 // components horizontally and vertically
10 setLayout( new GridLayout( 3 , 2 , 5 , 5 ));
11
12 // Add labels and text fields to the frame
13 add( new JLabel( "First Name" ));
14 add( new JTextField( 8 ));
15 add( new JLabel( "MI" ));
16 add( new JTextField( 1 ));
17 add( new JLabel( "Last Name" ));
18 add( new JTextField( 8 ));
19 }
20
21 /** Main method */
22 public static void main(String[] args) {
23 ShowGridLayout frame = new ShowGridLayout();
24 frame.setTitle( "ShowGridLayout" );
25 frame.setSize( 200 , 125 );
26 frame.setLocationRelativeTo( null ); // Center the frame
27 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
28 frame.setVisible( true );
29 }
30 }
set layout
add label
add text field
create the frame
set visible
If you resize the frame, the layout of the components remains unchanged (i.e., the number of
rows and columns does not change, and the gaps don't change either).
All components are given equal size in the container of GridLayout .
Replacing the setLayout statement (line 10) with setLayout(new GridLayout(3,
10)) would still yield three rows and two columns. The columns parameter is ignored
 
 
Search WWH ::




Custom Search