Java Reference
In-Depth Information
hosts, there may be no native window toolkit other than that provided by the Java run-
time; on others, the amount of memory consumed by the peer hierarchy would be too
great for the platform to support. To get around this, as you have already learned, the PBP
does not contain a full user-interface hierarchy for your application development. In fact,
the PBP explicitly
excludes
heavyweight components such as text labels, text input boxes,
buttons, lists, and menus. Instead, it requires the following four AWT top-level compo-
nent classes:
•
java.awt.Component
: The base class for all user-interface components
•
java.awt.Container
: The base class for AWT components that contain other
components
•
java.awt.Frame
: A top-level window with a title bar and a border
•
java.awt.Window
: The base class for top-level windows
Believe it or not, these four core component classes are enough to implement an
entire window toolkit, because the
Component
and
Container
classes can represent com-
ponents including nested components, and the
Frame
and
Window
classes permit you to
define top-level windows that contain those components. Of course, the PBP-required
AWT subset includes a host of additional classes that permit you to implement your
user interface, including
java.awt.Graphics
,
java.awt.Image
, and
java.awt.AWTEvent
.
This leaves you with just two choices for building an application that uses a GUI,
as you saw in the previous section: you can either use one in a package provided by
someone else, or you can roll your own. The Java community has defined several such
window toolkits, including more of the standard Java classes for the UI (AWT and/or
Swing, depending on the profile and packages on the target), and there are others such
as the HAVi hierarchy for BD-J. In addition, creating your own hierarchy may well be
feasible for your application, especially if your user interface has simple requirements.
Implementing Your Own Components for a Window Toolkit
In the Java user-interface paradigm, a
component
is any object that has a graphical repre-
sentation that can be displayed on the screen and interact with the user. A
container
is a
component that can also contain other components. When implementing your own GUI,
most of the work you need to do involves creating your own primitive components, such
as buttons. This involves implementing subclasses of
java.awt.Component
.
The key to implementing your own toolkit is handling the drawing for each of your
toolkit's components. Typically, this happens for one of two reasons: system-triggered
painting occurs, such as when the component is made visible on the screen or is resized,
or application-triggered painting occurs, when the component decides it needs to
repaint itself because its contents have changed. The AWT contract—which you must