joshreesjones
joshreesjones

Reputation: 1954

Why can I not call add() on a JFrame and instead must call it on a Container?

I am reading Head First Java. When introducing GUIs (page 354 for those of you who have the book), the author writes:

frame.getContentPane().add(button);

"You don't add things to the frame directly. Think of the frame as the trim around the window, and you add things to the window pane."

After looking at the Java API entry for JFrame, I saw that JFrame is a subclass of Component and inherits the add(Component) from Component, so it would work to simply write:

frame.add(button);

Why does the book recommend to use frame.getContentPane.add(button)?

Thanks in advance!

Upvotes: 3

Views: 91

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You can call add(...) on the JFrame, but what it does is in fact call getContentPane().add(...) as per the JFrame API and otherwise known as "syntactic sugar". But understand that in doing this, you aren't in fact adding it directly to the JFrame but in fact are adding it to the contentPane. This is important since the JFrame is made of a composition of components as the JFrame/top level window Swing Tutorial well explains.

Myself, I prefer the literal getContentPane().add(...) because not all JFrame behaviors will work this way, such as setBackground(...), and so being literal reminds me exactly what I am doing.

Upvotes: 6

Related Questions