Java Reference
In-Depth Information
From this discussion, it sounds as though you can place only one item in each
region, but later in this chapter, when we discuss
panels
, you will see that there is a way
to group items so that more than one item can (in effect) be placed in each region.
There are some standard layout managers defined for you in the
java.awt
package,
and you can also define your own layout managers. However, for most purposes, the
layout managers defined in the standard libraries are all that you need, and we will not
discuss how you can create your own layout manager classes.
Flow Layout Managers
The
FlowLayout
manager
is the simplest layout manager. It arranges components
one after the other, going from left to right, in the order in which you add them to
the
JFrame
(or other container class) using the method
add
. For example, if the class
in Display 17.7 had used the
FlowLayout
manager instead of the
BorderLayout
manager, it would have used the following code:
setLayout(
new
FlowLayout());
JLabel label1 =
new
JLabel("First label");
add(label1);
JLabel label2 =
new
JLabel("Second label");
add(label2);
JLabel label3 =
new
JLabel("Third label");
add(label3);
Layout Managers
The components that you add to a container class are arranged by an object known as a
layout manager
. Add a layout manager with the method
setLayout
, which is a method of
every container class, such as a
JFrame
or an object of any of the other container classes
that we will introduce later in this chapter. If you do not add a layout manager, a default
layout manager will be provided for you.
SYNTAX
Container_Object
.setLayout(
new
Layout_Manager_Class
());
EXAMPLE (WITHIN A CONSTRUCTOR FOR A CLASS CALLED
BorderLayoutJFrame
)
public
BorderLayoutJFrame()
{
...
setLayout(
new
BorderLayout());
JLabel label1 =
new
JLabel("First label");
add(label1, BorderLayout.NORTH);
JLabel label2 =
new
JLabel("Second label");
add(label2, BorderLayout.SOUTH);
...
}