简体   繁体   English

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

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

它们之间是否有区别,是否有任何条件可以使用一种而不是另一种?

Both calls are the same. 这两个电话是相同的。 In Java 5, they changed jframe.add to forward calls to the content pane. 在Java 5中,他们更改了jframe.add以将调用转发到内容窗格。

From the Java 5 release notes : Java 5发行说明中

Lastly, after seven years, we've made jFrame.add equivalent to jFrame.getContentPane().add(). 最后,七年后,我们使jFrame.add等效于jFrame.getContentPane()。add()。

Also, see the javadocs . 另外,请参阅javadocs

如果您的问题仅涉及JFrame#add(JComponent)JFrame.getContentPane()#add(JComponent) ,则没有区别,但是如果要更改fe BackGround,则取决于是否从JFrame#setBackground(Color)或从awt.Frame JFrame.getContentPane()#setBackground(Color)嵌套或继承方法...

From what I understand from Javadocs, JFrame.add calls the latter. 据我从Javadocs了解,JFrame.add称为后者。 It is a convenience method to get around the incompatibility between AWT's frame and Swings JFrame. 这是避免AWT框架与Swings JFrame之间不兼容的一种便捷方法。

From javadocs for JFrame : javadocs的JFrame

The JFrame class is slightly incompatible with Frame. JFrame类与Frame略有不兼容。 Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. 像所有其他JFC / Swing顶级容器一样,JFrame包含JRootPane作为其唯一的子级。 The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. 根窗格提供的内容窗格通常应包含JFrame显示的所有非菜单组件。 This is different from the AWT Frame case. 这与AWT框架情况不同。 As a conveniance add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. 为方便起见,add和setLayout被覆盖,可以根据需要转发到contentPane。 This means you can write: 这意味着您可以编写:

  `frame.add(child);` 

And the child will be added to the contentPane. 并将子级添加到contentPane中。 The content pane will always be non-null. 内容窗格将始终为非空。 Attempting to set it to null will cause the JFrame to throw an exception. 尝试将其设置为null将导致JFrame引发异常。 The default content pane will have a BorderLayout manager set on it. 默认的内容窗格将设置有BorderLayout管理器。 Refer to RootPaneContainer for details on adding, removing and setting the LayoutManager of a JFrame. 有关添加,删除和设置JFrame的LayoutManager的详细信息,请参考RootPaneContainer。

add() will forward the work to addImpl() for which the JavaDoc of JFrame states the following: add()将工作转发到addImpl()JFrame的JavaDoc为此指出:

By default, children are added to the contentPane instead of the frame. 默认情况下,将子级添加到contentPane而不是框架。

Thus, both methods have the same basic behaviour, besides the fact that using getContentPane().add(...) is more explicit. 因此,除了使用getContentPane().add(...)更明确的事实之外,这两种方法都具有相同的基本行为。

Note that you could alter the default behaviour for add (using setRootPaneCheckingEnabled(false) ), but I'm not sure you'd want to do that. 请注意,您可以更改add的默认行为(使用setRootPaneCheckingEnabled(false) ),但是我不确定您是否愿意这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM