Java Reference
In-Depth Information
12.5.1 FlowLayout
FlowLayout
is the simplest layout manager. The components are arranged in the container
from left to right in the order in which they were added. When one row is filled, a new row is
started. You can specify the way the components are aligned by using one of three constants:
FlowLayout.RIGHT
,
FlowLayout.CENTER
, or
FlowLayout.LEFT
. You can also specify
the gap between components in pixels. The class diagram for
FlowLayout
is shown in
Figure 12.4.
VideoNote
Use
FlowLayout
The
get
and
set
methods for these data
fields are provided in the class, but
omitted in the UML diagram for brevity.
java.awt.FlowLayout
-alignment: int
-hgap: int
-vgap: int
The alignment of this layout manager (default:
CENTER
).
The horizontal gap between the components (default: 5 pixels).
The vertical gap between the components (default: 5 pixels).
+FlowLayout()
+FlowLayout(alignment: int)
+FlowLayout(alignment: int, hgap:
int, vgap: int)
Creates a default
FlowLayout
manager.
Creates a
FlowLayout
manager with a specified alignment.
Creates a
FlowLayout
manager with a specified alignment,
horizontal gap, and vertical gap.
F
IGURE
12.4
FlowLayout
lays out components row by row.
Listing 12.3 gives a program that demonstrates flow layout. The program adds three labels
and text fields to the frame with a
FlowLayout
manager, as shown in Figure 12.5.
L
ISTING
12.3
ShowFlowLayout.java
1
import
javax.swing.JLabel;
2
import
javax.swing.JTextField;
3
import
javax.swing.JFrame;
4
import
java.awt.FlowLayout;
5
6
public class
ShowFlowLayout
extends
JFrame
{
extends
JFrame
7
public
ShowFlowLayout() {
8
// Set FlowLayout, aligned left with horizontal gap 10
9
// and vertical gap 20 between components
10 setLayout(
new
FlowLayout(FlowLayout.LEFT,
10
,
20
)
);
set layout
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 ShowFlowLayout frame =
new
ShowFlowLayout();
24 frame.setTitle(
"ShowFlowLayout"
);
25 frame.setSize(
200
,
200
);
add label
add text field