开发者

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

Is 开发者_如何学Gothere a difference between them and are there any conditions in which one should be used instead of the other?


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.


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.


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) ...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜