Java Reference
In-Depth Information
and the
gridheight
variable specifies the number of rows the
Component
will span in the
grid. Line 76 sets the
GridBagConstraints
for a component in the
GridBagLayout
. Meth-
od
setConstraints
of class
GridBagLayout
takes a
Component
argument and a
GridBag-
Constraints
argument. Line 77 adds the component to the
JFrame
.
When you execute this application, try resizing the window to see how the constraints
for each GUI component affect its position and size in the window.
GridBagConstraints
Constants
RELATIVE
and
REMAINDER
Instead of
gridx
and
gridy
, a variation of
GridBagLayout
uses
GridBagConstraints
con-
stants
RELATIVE
and
REMAINDER
.
RELATIVE
specifies that the next-to-last component in a
particular row should be placed to the right of the previous component in the row.
REMAINDER
specifies that a component is the last component in a row. Any component that
is not the second-to-last or last component on a row must specify values for
GridbagCon-
straints
variables
gridwidth
and
gridheight
. The application in Figs. 22.23-22.24 ar-
ranges components in
GridBagLayout
, using these constants.
1
// Fig. 22.23: GridBagFrame2.java
2
// Demonstrating GridBagLayout constants.
3
import
java.awt.GridBagLayout;
4
import
java.awt.GridBagConstraints;
5
import
java.awt.Component;
6
import
javax.swing.JFrame;
7
import
javax.swing.JComboBox;
8
import
javax.swing.JTextField;
9
import
javax.swing.JList;
10
import
javax.swing.JButton;
11
12
public
class
GridBagFrame2
extends
JFrame
13
{
14
private final
GridBagLayout layout;
// layout of this frame
15
private final
GridBagConstraints constraints;
// layout's constraints
16
17
// set up GUI
18
public
GridBagFrame2()
19
{
20
super
(
"GridBagLayout"
);
21
layout =
new
GridBagLayout();
setLayout(layout);
// set frame layout
22
23
constraints =
new
GridBagConstraints();
// instantiate constraints
24
25
// create GUI components
26
String[] metals = {
"Copper"
,
"Aluminum"
,
"Silver"
};
27
JComboBox comboBox =
new
JComboBox(metals);
28
29
JTextField textField =
new
JTextField(
"TextField"
);
30
31
String[] fonts = {
"Serif"
,
"Monospaced"
};
32
JList list =
new
JList(fonts);
33
Fig. 22.23
|
GridBagConstraints
constants
RELATIVE
and
REMAINDER
. (Part 1 of 2.)