Why do we have to add components to a JFrame’s content?
Q: Why do we have to add components to a JFrame’s content pane? Why can’t we just add it directly to the frame like in the AWT?
A:
Actually, “because” is almost a good enough answer here. However, it may make a little more sense if you look at the way Swing defines top-level containers such as the JFrame
. All top-level containers contain one component: an instance of JRootPane
. The JRootPane
contains a JPanel glassPane
and a JLayeredPane
. Going deeper, the JLayeredPane
further contains a JMenuBar
and a JPanel contentPane
. The container nesting gives us a logical containment hierarchy.
Requiring you to insert components into the contentPane
forces you to follow the containment hierarchy. Instead of inserting components anywhere, you must insert components into the contentPane
where they belong by design. A top-level container contains only one component: the JRootPane
instance. The JRootPane
then nests all of the other components. Trying to add components to a JFrame
directly makes no sense since the frame is meant to contain only one component directly.
But wait a minute; why design it this way?
By placing components into the contentPane
, you always know where your “content” components are. This allows you to take advantage of the glassPane
and layer
s directly. If a component could appear anywhere, say above a glassPane
, you couldn’t easily block that component from events by using the glassPane
. Furthermore, you couldn’t automatically put another layer on top of the component since it may reside outside of the JLayeredPane
completely.
By following the containment hierarchy, you automatically benefit from the other parts of the hierarchy. If you circumvent the hierarchies, you have to worry about maintaining look and feel as well as supporting layer
– and glassPane
-like features yourself. If there weren’t a hierarchy, there wouldn’t be a convenient, standard way of layering content or blocking events. You would have to reinvent some kind of mechanism for each GUI that you write.
So take it easy on yourself, trust the design, and just put your components where they belong!