Java Reference
In-Depth Information
This was cumbersome. Versions of Java since Java 5 allow you to place components in the
content pane by invoking a frame's
add
method, as follows:
frame.add(jbtOK);
This feature is called
content-pane delegation
. Strictly speaking, a component is added to the
content pane of a frame. For simplicity, we say that a component is added to a frame.
In Listing 12.2, an object of
JButton
was created using
new JButton("OK")
, and this
object was added to the content pane of the frame (line 9).
The
add(Component comp)
method defined in the
Container
class adds an
instance of
Component
to the container. Since
JButton
is a subclass of
Component
, an
instance of
JButton
is also an instance of
Component
. To remove a component from a
container, use the
remove
method. The following statement removes the button from the
container:
content-pane delegation
container.remove(jbtOK);
When you run the program
MyFrameWithComponents
, the window will be displayed as in
Figure 12.3b. The button is always centered in the frame and occupies the entire frame no
matter how you resize it. This is because components are put in the frame by the content
pane's layout manager, and the default layout manager for the content pane places the button
in the center. In the next section, you will use several different layout managers to place com-
ponents in the desired locations.
12.5
How do you create a frame? How do you set the size for a frame? How do you
add components to a frame? What would happen if the statements
frame.setSize(400, 300)
and
frame.setVisible(true)
were swapped in
Listing 12.2?
✓
✓
Check
Point
Each container contains a layout manager, which is an object responsible for laying
out the GUI components in the container.
Key
Point
In many other window systems, the user-interface components are arranged by using hard-
coded pixel measurements. For example, when placing a button at location (
10, 10
) in a
window using hard-coded pixel measurements, the user interface might look fine on one sys-
tem but be unusable on another. Java's
layout managers
provide a level of abstraction that
automatically maps your user interface on all window systems.
The Java GUI components are placed in containers, where they are arranged by the con-
tainer's layout manager. In the preceding program, you did not specify where to place the
OK
button in the frame, but Java knows where to place it, because the layout manager works
behind the scenes to place components in the correct locations. A layout manager is created
using a layout manager class.
Layout managers are set in containers using the
setLayout(aLayoutManager)
method.
For example, you can use the following statements to create an instance of
XLayout
and set
it in a container:
layout manager
LayoutManager layoutManager =
new
XLayout();
container.setLayout(layoutManager);
This section introduces three basic layout managers:
FlowLayout
,
GridLayout
, and
BorderLayout
.