我知道,从Java 1.5开始,可以向JFrame添加一个组件,如下所示:
myFrame.add(myButton的);
代替:
myFrame.getContentPane()添加(myButton的).
为什么总是这样呢?
正如JFrame API中所述,两者都做同样的事情:向contentPane添加一个组件.它刚刚出现(也许是Java 1.5?)Swing添加了语法糖/便利方法,允许您直接在JFrame(或任何其他Swing顶级容器)上进行此调用,但您仍在添加到contentPane.相同的remove(...)和setLayout(...)如果您尝试通过设置JFrame的背景颜色myJFrame.setBackground(Color.green);并且没有任何反应,这一点就变得非常清楚了.正是出于这个原因,我对这一变化并不满意.那也是因为我必须是一个古老的吝啬鬼.
4753342:Swing的顶级组件应该将添加/删除方法重定向到ContentPane
描述:相反,AWT编程,
JFrame/JDialg/JWindow/JApplet/JInternalFrame不允许你添加Components到它,而必须了解JRootPane和孩子添加Components到它.这给新开发者增加了不必要的困惑.在5.0之前,尝试
Component从这些顶级Components 之一添加或删除a 将导致抛出异常.在5.0中,不会抛出任何异常,而是Component将从内容窗格中添加或删除.这导致了一些修订的javadoc的JFrame,JDialog,JWindow,JApplet和JInternalFrame.这已经在RootPaneContainer的javadoc中进行了总结:Run Code Online (Sandbox Code Playgroud)* 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.
另外,这是一个相关的错误: