这两个调用是相同的。在Java 5中,它们将jframe.add
更改为转发调用到内容面板。
从Java 5发布说明中:
最后,经过七年,我们已经使jFrame.add等效于jFrame.getContentPane().add()。
另请参见javadocs 。
据我所了解,JFrame.add 调用的是后者。这是一种方便的方法,可以解决 AWT 框架和 Swing 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.
JFrame#add(JComponent)
和JFrame.getContentPane()#add(JComponent)
之间的区别,那么它们是没有区别的。但如果你想更改例如背景颜色,那么就要看你是从JFrame#setBackground(Color)
调用方法还是从继承自awt.Frame的嵌套方法或继承方法JFrame.getContentPane()#setBackground(Color)
...add()
方法会将工作转发给addImpl()
方法,其中JFrame
的JavaDoc说明如下:
默认情况下,子组件会添加到contentPane而非frame中。
因此,这两种方法具有相同的基本行为,除了使用getContentPane().add(...)
更加明确。
请注意,您可以更改add的默认行为(使用setRootPaneCheckingEnabled(false)
),但我不确定您是否想要这样做。