为什么JFrame最初需要getContentPane()来添加组件

Ell*_*tus 8 java swing jframe

我知道,从Java 1.5开始,可以向JFrame添加一个组件,如下所示:

myFrame.add(myButton的);

代替:

myFrame.getContentPane()添加(myButton的).

为什么总是这样呢?

Hov*_*els 9

正如JFrame API中所述,两者都做同样的事情:向contentPane添加一个组件.它刚刚出现(也许是Java 1.5?)Swing添加了语法糖/便利方法,允许您直接在JFrame(或任何其他Swing顶级容器)上进行此调用,但您仍在添加到contentPane.相同的remove(...)setLayout(...)如果您尝试通过设置JFrame的背景颜色myJFrame.setBackground(Color.green);并且没有任何反应,这一点就变得非常清楚了.正是出于这个原因,我对这一变化并不满意.那也是因为我必须是一个古老的吝啬鬼.

  • 这个概念让新手们相信JFrame实际上是获得组件的东西.**再次**尝试在JFrame上调用setBackground(...). (3认同)
  • 这是一种分而治之的哲学.JFrame本身同意创建一个必须包含本机代码并构建在本机GUI组件上的窗口.顶级窗口中的所有其他组件都很轻,每个组件都执行自己的角色 - contentPane用于保存添加到GUI中的所有组件并将其布局,菜单栏用于保存菜单,玻璃板用于覆盖所有和根窗格以保存它们. (2认同)

mre*_*mre 7

4753342:Swing的顶级组件应该将添加/删除方法重定向到ContentPane

描述:

相反,AWT编程, JFrame/ JDialg/ JWindow/ JApplet/ JInternalFrame不允许你添加 Components到它,而必须了解JRootPane和孩子添加Components到它.这给新开发者增加了不必要的困惑.

在5.0之前,尝试Component从这些顶级Components 之一添加或删除a 将导致抛出异常.在5.0中,不会抛出任何异常,而是Component将从内容窗格中添加或删除.这导致了一些修订的javadoc的JFrame,JDialog,JWindow,JAppletJInternalFrame.这已经在RootPaneContainer的javadoc中进行了总结:

 * For conveniance
 * <code>JFrame</code>, <code>JDialog</code>, <code>JWindow</code>,
 * <code>JApplet</code> and <code>JInternalFrame</code>, by default,
 * forward all calls to <code>add</code> and its variants,
 * <code>remove</code> and <code>setLayout</code> to the
 * <code>contentPane</code>. This means rather than writing:
 * <pre>
 * rootPaneContainer.getContentPane().add(component);
 * </pre>
 * you can do:
 * <pre>
 * rootPaneContainer.add(component);
 * </pre>
 * <p>
 * The behavior of <code>add</code> and its variants and
 * <code>setLayout</code> for
 * <code>JFrame</code>, <code>JDialog</code>, <code>JWindow</code>,
 * <code>JApplet</code> and <code>JInternalFrame</code> is controlled by
 * the <code>rootPaneCheckingEnabled</code> property. If this property is
 * true, the default, then <code>add</code> and its variants and
 * <code>setLayout</code> are
 * forwarded to the <code>contentPane</code>, if it is false, then these
 * methods operate directly on the <code>RootPaneContainer</code>. This
 * property is only intended for subclasses, and is therefor protected.
Run Code Online (Sandbox Code Playgroud)

另外,这是一个相关的错误: