Java Reference
In-Depth Information
17.2.6
Lightweight versus heavyweight
Skip this advanced topic on first reading.
You may wonder how a component is actually drawn on a window. Each
component in the old java.awt is associated with a “native” program —one
written in the machine language— that does the actual drawing. This native pro-
gram is called the component's peer . Any component that has such an associat-
ed peer component is called heavyweight .
In the newer Swing package, the only heavyweight components are top-
level ones: JWindow , JFrame , JDialog , and JApplet . All the others, like JBut-
ton and JTextArea , are called lightweight because they do not have an associ-
ated peer. They rely on the objects in which they are placed —ultimately one of
the top-level components— to do the drawing for them. Since they do not have
associated peer programs, they are “lighter”.
In theory, you can mix lightweight and heavyweight components. In a light-
weight JPanel , for example, you should be able to place a heavyweight Button
and a lightweight JButton . But this mixing of components does not always work
well because the two kinds of components have different properties. Therefore,
if you have a choice, do not mix. Use components of the Swing package, wher-
ever possible, or stick completely to the old java.awt package.
Here are two differences between lightweight and heavyweight components:
1. A lightweight component can have transparent pixels, so you may see
whatever is underneath. A heavyweight component is always opaque.
2. Mouse events on a lightweight component fall through to its parent —the
container to which it was added. Mouse events on a heavyweight com-
ponent do not fall through.
There are other differences, but these should be enough for you to see why
mixing lightweight and heavyweight components might create inconsistency that
could lead to problems.
Sun's web page for Java discusses lightweight versus heavyweight compo-
nents. The last time we looked, this issue was discussed at URL:
http://java.sun.com/products/jfc/tsc/articles/mixing/
Figure 17.9:
A JFrame with a four-button JPanel in the center
Search WWH ::




Custom Search