Java Reference
In-Depth Information
1
// Fig. 22.24: GridBagDemo2.java
2
// Demonstrating GridBagLayout constants.
3
import
javax.swing.JFrame;
4
5
public
class
GridBagDemo2
6
{
7
public
static
void
main(String[] args)
8
{
9
GridBagFrame2 gridBagFrame =
new
GridBagFrame2();
10
gridBagFrame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE
);
11
gridBagFrame.setSize(
300
,
200
);
12
gridBagFrame.setVisible(
true
);
13
}
14
}
// end class GridBagDemo2
Fig. 22.24
|
Test class for
GridBagDemo2
.
Setting the
JFrame
's Layout to a
GridBagLayout
Lines 21-22 create a
GridBagLayout
and use it to set the
JFrame
's layout manager. The
components that are placed in
GridBagLayout
are created in lines 27-38—they are a
JComboBox
, a
JTextField
, a
JList
and five
JButton
s.
Configuring the
JTextField
The
JTextField
is added first (lines 41-45). The
weightx
and
weighty
values are set to
1. The
fill
variable is set to
BOTH
. Line 44 specifies that the
JTextField
is the last com-
ponent on the line. The
JTextField
is added to the content pane with a call to our utility
method
addComponent
(declared at lines 79-83). Method
addComponent
takes a
Compo-
nent
argument and uses
GridBagLayout
method
setConstraints
to set the constraints
for the
Component
. Method
add
attaches the component to the content pane.
Configuring
JButton
buttons[0]
JButton
buttons[0]
(lines 48-49) has
weightx
and
weighty
values of 1. The
fill
vari-
able is
BOTH
. Because
buttons[0]
is not one of the last two components on the row, it's
given a
gridwidth
of 1 and so will occupy one column. The
JButton
is added to the con-
tent pane with a call to utility method
addComponent
.