ksm001
ksm001

Reputation: 4022

when should I use JFrame.add(component) and JFrame.getContentPane().add(component) in java

Is there a difference between them and are there any conditions in which one should be used instead of the other?

Upvotes: 14

Views: 10555

Answers (4)

mKorbel
mKorbel

Reputation: 109823

if your question is only about JFrame#add(JComponent) v.s. JFrame.getContentPane()#add(JComponent) then there isn't difference, but if you want to change f.e. BackGround then depends if you call methods from JFrame#setBackground(Color) or nested or inherits methods from awt.Frame JFrame.getContentPane()#setBackground(Color) ...

Upvotes: 4

Ashkan Aryan
Ashkan Aryan

Reputation: 3534

From what I understand from Javadocs, JFrame.add calls the latter. It is a convenience method to get around the incompatibility between AWT's frame and Swings JFrame.

From javadocs for JFrame:

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. As a conveniance add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. This means you can write:

   `frame.add(child);`

And the child will be added to the contentPane. The content pane will always be non-null. Attempting to set it to null will cause the JFrame to throw an exception. The default content pane will have a BorderLayout manager set on it. Refer to RootPaneContainer for details on adding, removing and setting the LayoutManager of a JFrame.

Upvotes: 4

dogbane
dogbane

Reputation: 274738

Both calls are the same. In Java 5, they changed jframe.add to forward calls to the content pane.

From the Java 5 release notes:

Lastly, after seven years, we've made jFrame.add equivalent to jFrame.getContentPane().add().

Also, see the javadocs.

Upvotes: 14

Thomas
Thomas

Reputation: 88727

add() will forward the work to addImpl() for which the JavaDoc of JFrame states the following:

By default, children are added to the contentPane instead of the frame.

Thus, both methods have the same basic behaviour, besides the fact that using getContentPane().add(...) is more explicit.

Note that you could alter the default behaviour for add (using setRootPaneCheckingEnabled(false)), but I'm not sure you'd want to do that.

Upvotes: 3

Related Questions