我知道,as of Java 1.5,可以將組件添加到這樣一個JFrame:爲什麼JFrame的最初要求的getContentPane()添加組件
myFrame.add(myButton的);
代替:
myFrame.getContentPane()添加(myButton的);
爲什麼不總是這種情況?
我知道,as of Java 1.5,可以將組件添加到這樣一個JFrame:爲什麼JFrame的最初要求的getContentPane()添加組件
myFrame.add(myButton的);
代替:
myFrame.getContentPane()添加(myButton的);
爲什麼不總是這種情況?
正如在JFrame API中闡述的那樣,兩者都做同樣的事情:將一個組件添加到contentPane。這只是最近的事情(Java 1.5或許?)Swing添加了語法糖/便捷方法,允許您直接在JFrame(或任何其他Swing頂級容器)上調用此調用,但是您仍在添加到contentPane。 remove(...)
和setLayout(...)
相同如果您嘗試通過myJFrame.setBackground(Color.green);
設置JFrame的背景顏色並且什麼也沒有發生,這將變得非常清晰。正因爲如此,我對這個改變並不滿意。那也是因爲我必須是一個古老的謬論。
你能告訴我你爲什麼不滿意這個變化嗎?我試圖理解反對它的論點。 – 2012-02-07 01:44:11
這個概念引導新手相信JFrame實際上是獲取組件的東西。 **再次**嘗試在JFrame上調用setBackground(...)。 – 2012-02-07 01:47:23
謝謝。爲什麼不把JFrame放在首位,所以setBackground()可以滿足人們的期望? – 2012-02-07 01:54:00
4753342:Swing的頂層組件應該重定向添加/刪除 方法的contentPane
說明:相反,AWT編程,
JFrame
/JDialg
/JWindow
/JApplet
/JInternalFrame
不允許您添加Component
s,而您必須瞭解JRootPane
並添加 孩子Component
就是了。這增加了對新開發人員不必要的困惑。在5.0之前,試圖從 之一添加或刪除
Component
這些頂級Component
會導致拋出異常。在 5.0中,不會拋出異常,而是將從內容窗格中添加或刪除Component
。這導致了若干修訂 到javadocJFrame
,JDialog
,JWindow
,JApplet
和JInternalFrame
。這已經總結在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.
而且,這裏有一個相關的錯誤:
非常有用的信息! 1+ – 2012-02-07 02:01:44
非常有幫助,謝謝。 – Alanmars 2012-02-07 06:51:12
我詢問原因,是我教介紹CS和書中的例子都使用舊的符號。我希望能夠給學生一些理由說明爲什麼一度需要做額外的步驟。 – 2012-02-07 01:33:47