Java Reference
In-Depth Information
Containers and Components
There are two basic elements of a GUI: containers and components. A con-
tainer is for displaying components, and components must be displayed
within a container. A Button is an example of a component, whereas a Frame is
an example of a container. To display a Button, you place it within a Frame and
display the Frame.
Component is an abstract class that is the parent class of the various GUI
components of the AWT: Button, Checkbox, Choice, Label, List, and Text-
Component. Container is an abstract class that is the parent class of the
containers of the AWT: Window, Panel, and ScrollPane. Child objects of Com-
ponent are placed within child objects of Container. For example, a Button can
be placed within a Panel, or a List can be placed within a Frame.
Components are placed inside containers. However, notice that Container
is a child of Component. Therefore, a container is a component, which
allows a Container object to be placed inside another Container object.
For example, a Panel is a Container, and a Frame is a Container. Because
Panel is also a Component, a Panel can be placed inside a Frame. (Using
the same logic, a Frame can also be placed inside a Panel.)
The nesting of containers is an important aspect of creating the look of
your GUI. The section Panels later in this chapter shows you how to add a
Panel to a Frame and demonstrates why this is commonly done.
The JComponent class is a child of Container, and it is the parent class of all
of the Swing components, such as JComboBox, JLabel, JSlider, JSpinner, and
JMenuBar. One of the ways that Swing is different from AWT is that not all
AWT components are containers. However, all Swing components extend
JComponent, which extends Container. Therefore, all Swing components are
also containers, allowing them to be nested within each other. For example, a
JButton can be placed within a JFrame (a typical use of JButton). However,
because JButton is a child of Container, you can place a JFrame inside a JButton
(which is not a typical GUI feature, but nonetheless this can be done in Swing).
Adding Components to a Container
A Component is added to a Container using one of the following add() methods
found in the java.awt.Container class:
public Component add(Component c). Adds the Component to the
Container and returns a reference to the newly added Component
Search WWH ::




Custom Search