Java Reference
In-Depth Information
Layout Managers
The components that you add to a container class are arranged by an object known as a
lay-
out manager
. You 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);
...
}
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);
Note that if we had used the
FlowLayout
manager, as in the preceding code, then the
add
method would have only one argument. With a
FlowLayout
manager, the items
are displayed in the order they are added, so that the labels above would be displayed
all on one line as follows:
First label Second label Third label