Java Reference
In-Depth Information
The default for
JFrame
and
JWindow
is
BorderLayout
. This explains the problem of the
single button appearing in the
JFrameDemo
class at the end of the previous recipe.
Border-
Layout
divides the screen into the five areas shown in
Figure 14-1
. If you don't specify
where to place a component, it goes into the center. And if you place multiple components in
the same region (perhaps by adding several components without specifying where to place
them!), only the last one appears.
Figure 14-1. BorderLayout's five regions
So we can fix the previous version of the
JFrameDemo
in one of two ways: either we can use
a
FlowLayout
or specify
BorderLayout
regions for the label and the button. The former be-
ing simpler, we'll try it out:
public
public class
class
JFrameFlowLayout
JFrameFlowLayout
extends
extends
JFrame
{
public
public
JFrameFlowLayout
() {
Container cp
=
getContentPane
();
// Make sure it has a FlowLayout layoutmanager.
cp
.
setLayout
(
new
new
FlowLayout
());
// now add Components to "cp"...
cp
.
add
(
new
new
JLabel
(
"Wonderful?"
));
cp
.
add
(
new
new
JButton
(
"Yes!"
));
pack
();
}