何时应该在Java中使用JFrame.add(component)和JFrame.getContentPane().add(component)?

14
它们之间有区别吗?在什么情况下应该使用其中一个而不是另一个?
4个回答

14

这两个调用是相同的。在Java 5中,它们将jframe.add更改为转发调用到内容面板。

Java 5发布说明中:

最后,经过七年,我们已经使jFrame.add等效于jFrame.getContentPane().add()。

另请参见javadocs


4

据我所了解,JFrame.add 调用的是后者。这是一种方便的方法,可以解决 AWT 框架和 Swing JFrame 之间的不兼容问题。

来自JFrame 的 Javadocs

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.


4
如果你的问题只涉及到JFrame#add(JComponent)JFrame.getContentPane()#add(JComponent)之间的区别,那么它们是没有区别的。但如果你想更改例如背景颜色,那么就要看你是从JFrame#setBackground(Color)调用方法还是从继承自awt.Frame的嵌套方法或继承方法JFrame.getContentPane()#setBackground(Color)...

3
add()方法会将工作转发给addImpl()方法,其中JFrame的JavaDoc说明如下:

默认情况下,子组件会添加到contentPane而非frame中。

因此,这两种方法具有相同的基本行为,除了使用getContentPane().add(...)更加明确。

请注意,您可以更改add的默认行为(使用setRootPaneCheckingEnabled(false)),但我不确定您是否想要这样做。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接