2012-02-07 76 views
8

我知道,as of Java 1.5,可以将组件添加到这样一个JFrame:为什么JFrame的最初要求的getContentPane()添加组件

myFrame.add(myButton的);

代替:

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

为什么不总是这种情况?

+0

我询问原因,是我教介绍CS和书中的例子都使用旧的符号。我希望能够给学生一些理由说明为什么一度需要做额外的步骤。 – 2012-02-07 01:33:47

回答

9

正如在JFrame API中阐述的那样,两者都做同样的事情:将一个组件添加到contentPane。这只是最近的事情(Java 1.5或许?)Swing添加了语法糖/便捷方法,允许您直接在JFrame(或任何其他Swing顶级容器)上调用此调用,但是您仍在添加到contentPane。 remove(...)setLayout(...)相同如果您尝试通过myJFrame.setBackground(Color.green);设置JFrame的背景颜色并且什么也没有发生,这将变得非常清晰。正因为如此,我对这个改变并不满意。那也是因为我必须是一个古老的谬论。

+0

你能告诉我你为什么不满意这个变化吗?我试图理解反对它的论点。 – 2012-02-07 01:44:11

+3

这个概念引导新手相信JFrame实际上是获取组件的东西。 **再次**尝试在JFrame上调用setBackground(...)。 – 2012-02-07 01:47:23

+0

谢谢。为什么不把JFrame放在首位,所以setBackground()可以满足人们的期望? – 2012-02-07 01:54:00

7

4753342:Swing的顶层组件应该重定向添加/删除 方法的contentPane

说明:

相反,AWT编程, JFrame/JDialg/JWindow/JApplet/JInternalFrame不允许您添加 Component s,而您必须了解JRootPane并添加 孩子Component就是了。这增加了对新开发人员不必要的困惑。

在5.0之前,试图从 之一添加或删除Component这些顶级Component会导致抛出异常。在 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. 

而且,这里有一个相关的错误:

+0

非常有用的信息! 1+ – 2012-02-07 02:01:44

+0

非常有帮助,谢谢。 – Alanmars 2012-02-07 06:51:12