Java Reference
In-Depth Information
FlowLayout
is the
simplest
layout manager. GUI components are placed in a container
from left to right in the order in which they're added to the container. When the edge of
the container is reached, components continue to display on the next line. Class
FlowLay-
out
allows GUI components to be
left aligned
,
centered
(the default) and
right aligned
.
The application of Figs. 12.39-12.40 creates three
JButton
objects and adds them to
the application, using a
FlowLayout
. The components are center aligned by default. When
the user clicks
Left
, the
FlowLayout
's alignment is changed to left aligned. When the user
clicks
Right
, the
FlowLayout
's alignment is changed to right aligned. When the user clicks
Center
, the
FlowLayout
's alignment is changed to center aligned. The sample output win-
dows show each alignment. The last sample output shows the centered alignment after the
window has been resized to a smaller width so that the button
Right
flows onto a new line.
As seen previously, a container's layout is set with method
setLayout
of class
Con-
tainer
. Line 25 (Fig. 12.39) sets the layout manager to the
FlowLayout
declared at line
23. Normally, the layout is set before any GUI components are added to a container.
Look-and-Feel Observation 12.17
Each individual container can have only one layout manager, but multiple containers in
the same application can each use different layout managers.
1
// Fig. 12.39: FlowLayoutFrame.java
2
// FlowLayout allows components to flow over multiple lines.
3
import
java.awt.FlowLayout;
4
import
java.awt.Container;
5
import
java.awt.event.ActionListener;
6
import
java.awt.event.ActionEvent;
7
import
javax.swing.JFrame;
8
import
javax.swing.JButton;
9
10
public
class
FlowLayoutFrame
extends
JFrame
11
{
12
private final
JButton leftJButton;
// button to set alignment left
13
private final
JButton centerJButton;
// button to set alignment center
14
private final
JButton rightJButton;
// button to set alignment right
15
private final
FlowLayout layout;
// layout object
16
private final
Container container;
// container to set layout
17
18
// set up GUI and register button listeners
19
public
FlowLayoutFrame()
20
{
21
super
(
"FlowLayout Demo"
);
22
23
layout =
new
FlowLayout();
24
container = getContentPane();
// get container to layout
25
setLayout(layout);
26
27
// set up leftJButton and register listener
28
leftJButton =
new
JButton(
"Left"
);
29
add(leftJButton);
// add Left button to frame
Fig. 12.39
|
FlowLayout
allows components to flow over multiple lines. (Part 1 of 2.)