FlowLayout
is a simple
layout manager that tries to arrange components at their preferred sizes,
from left to right and top to bottom in the container. A FlowLayout
can have a specified row
justification of LEFT
, CENTER
, or RIGHT
and a fixed
horizontal and vertical padding. By default, a flow layout uses CENTER
justification, meaning that all
components are centered within the area allotted to them. FlowLayout
is the default for JPanel
s.
The following example adds five buttons to the content pane of a
JFrame
using the default FlowLayout
:
//file: Flow.java
import
java.awt.*
;
import
java.awt.event.*
;
import
javax.swing.*
;
public
class
Flow
extends
JPanel
{
public
Flow
()
{
// FlowLayout is default layout manager for a JPanel
add
(
new
JButton
(
"One"
));
add
(
new
JButton
(
"Two"
));
add
(
new
JButton
(
"Three"
));
add
(
new
JButton
(
"Four"
));
add
(
new
JButton
(
"Five"
));
}
public
static
void
main
(
String
[]
args
)
{
JFrame
frame
=
new
JFrame
(
"Flow"
);
frame
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
frame
.
setSize
(
400
,
75
);
frame
.
setLocation
(
200
,
200
);
Flow
flow
=
new
Flow
();
frame
.
setContentPane
(
flow
);
frame
.
setVisible
(
true
);
}
}
The result is shown in Figure 19-2.
Try resizing the window. If it is made narrow enough, some of the buttons will spill over to a second or third row.
Get Learning Java, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.