Java Reference
In-Depth Information
Note that a layout manager is free to ignore some of its components; there is no requirement
that a layout manager display everything. For example, a
Container
using a
BorderLayout
might
include 30 or 40 components; however, the
BorderLayout
will display at most 5 of them (the last
component placed in each of its five named areas). Likewise, a
CardLayout
may manage many
components but displays exactly one at a time.
Besides ignoring components, a layout manager can do anything it wants with the compo-
nents' minimum, preferred, and maximum size. It is free to ignore any or all of these. It makes
sense that a layout manager can ignore a
preferred
size—after all, preferred means, “Give me
this size if it's available.” However, a layout manager can also ignore a minimum size. At times,
there is no reasonable alternative because the container may not have enough room to display
a component at its minimum size. How to handle this situation is left to the layout manager
designer's discretion.
LayoutManager Interface
The
LayoutManager
interface defines the responsibilities of the manager that lays out the
Component
objects within a
Container
. As explained in the previous section, it is the duty of the
layout manager to determine the position and size of each component within the
Container
.
You will never call the methods of the
LayoutManager
interface directly; for the most part, layout
managers do their work behind the scenes. Once you have created a
LayoutManager
object and
told the container to use it (by calling
setLayout(manager)
), you're finished with it. The system
calls the appropriate methods of the layout manager when necessary. Like any interface,
LayoutManager
specifies the methods a layout manager must implement but says nothing
about how the
LayoutManager
does its job.
The
LayoutManager
interface itself is most important if you are writing a new layout manager.
I'll describe this interface first because it's the foundation on which all layout managers are
based. I'll also describe the
LayoutManager2
interface, which is used by some layout managers.
Exploring the LayoutManager Interface
Five methods make up the
LayoutManager
interface:
public interface LayoutManager {
public void addLayoutComponent(String name, Component comp);
public void layoutContainer(Container parent);
public Dimension minimumLayoutSize(Container parent);
public Dimension preferredLayoutSize(Container parent);
public void removeLayoutComponent(Component comp);
}