Java Reference
In-Depth Information
17.3
Containers and Layout Managers
Don't put all your eggs in one basket.
PROVERB
There are two main ways to create new classes from old classes. One way is to use
inheritance; this is known as the Is-A relationship. For example, an object of the class
ColoredWindow in Display 17.6 is a JFrame because ColoredWindow is a derived class of
the class JFrame . The second way to create a new class from an existing class (or classes) is
to have instance variables of an already existing class type; this is known as composition or
the Has-A relationship. The Swing library has already set things up so you can easily use
composition. The actual code for declaring instance variables is in the Swing library
classes, such as the class JFrame . Rather than declaring instance variables, you add com-
ponents to a JFrame using the add method. This does ultimately set some instance vari-
ables, but that is done automatically when you use the add method. In this section, we
discuss adding and arranging components in a GUI or subpart of a GUI.
Thus far, we have only added one component, either a button or a label, to a JFrame .
You can add more than one component to a JFrame . To do so, you use the add method
multiple times, but the add method simply tells which components are added to the
JFrame ; it does not say how they are arranged, such as side by side or one above the
other. To describe how the components are arranged, you need to use a layout manager .
In this section, we will see that there are other classes of objects besides JFrame s that
can have components added with the add method and arranged by a layout manager.
All these classes are known as container classes .
layout
manager
container
class
Border Layout Managers
Display 17.7 contains an example of a GUI that uses a layout manager to arrange
three labels in a JFrame . The labels are arranged one below the other on three lines.
A layout manager is added to the JFrame class in Display 17.7 with the following
line:
setLayout
setLayout( new BorderLayout());
BorderLayout is a layout manager class, so new BorderLayout() produces a new anon-
ymous object of the class BorderLayout . This BorderLayout object is given the task of
arranging components (in this case, labels) that are added to the JFrame .
It may help to note that the above invocation of setLayout is equivalent to the
following:
Border-
Layout
BorderLayout manager = new BorderLayout();
setLayout(manager);
Search WWH ::




Custom Search