Lightweight vs. Heavyweight Components

The issue of lightweight and heavyweight components has plagued Swing since its early days. What has confused the majority of programmers from the start is the idea of z-order, or layering, among the Swing lightweight components and the AWT heavyweight components.

Understanding the Z-Order

In Swing, it might help to think of a heavyweight component as an artist’s easel. Recall that top-level components in Swing (JWindow, JDialog, JApplet, and JFrame) are heavyweight, everything else isn’t. Lightweight components that are added to those top-level heavyweights can be thought of as drawings on the canvas of each easel. Therefore, if another heavyweight component (another easel) is moved in front of the original easel, or even attached to it, the lightweight paintings on the original easel are obscured; Figure 28.6 demonstrates this analogy.

The same is true for how Swing interprets the z-order of lightweight and heavyweight components, even in a container. If a heavyweight component is added to a container that has lightweight components, the heavyweight will always be on top; the lightweight components must share the same z-order as the parent container. In addition, lightweight components cannot draw themselves outside the container (easel) they reside in, or they will be clipped.

Consider heavyweight components as easels and lightweight components as drawings

Figure 28-6. Consider heavyweight components as easels and lightweight ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.