2012-02-07 2 views
8
내가 as of Java 1.5은, 하나는이 같은 JFrame의에 구성 요소를 추가 할 수 있습니다, 알고

추가하는 getContentPane()를 필요로 않았다왜 JFrame의 원래 구성 요소

myFrame.add (을 myButton를); 대신

:

myFrame.getContentPane() 추가 (을 myButton).

왜 항상 그렇지 않은가요?

+0

질문에 대한 나의 이유는 내가 소개 CS 등을 가르치고있는 이 책의 예제는 모두 오래된 표기법을 사용합니다.학생들에게 한때 여분의 조치를 취해야하는 이유를 설명 할 수 있기를 바랍니다. –

답변

9

JFrame API에 나와있는 것처럼, 둘 다 같은 것을 수행합니다. contentPane에 구성 요소를 추가합니다. Swing은 JFrame (또는 다른 Swing 최상위 컨테이너)에서이 호출을 직접 수행 할 수 있도록 구문 설탕/편의 메소드를 추가했지만 여전히 contentPane에 추가하고 있습니다. remove(...)setLayout(...)과 동일합니다. myJFrame.setBackground(Color.green);을 통해 JFrame의 배경색을 설정하려고해도 아무 것도 나타나지 않습니다. 아무 일도 일어나지 않습니다. 이런 이유로 나는이 변화에 너무 만족하지 않는다. 나는 또한 오래된 curmudgeon이어야합니다.

+0

변경 사항에 만족하지 않는 이유를 말씀해 주시겠습니까? 나는 그것에 대한 논쟁을 이해하려고 노력하고있다. –

+3

이 개념은 초보자가 JFrame이 실제로 구성 요소를 얻는 것이라고 믿게 만듭니다. ** 다시 ** JFrame에서 setBackground (...)를 호출 해보십시오. –

+0

감사합니다. 왜 setBackground()가 사람들이 기대하는대로 JFrame을 컨테이너로 만들지 않겠습니까? –

7

4,753,342 : 스윙의 최상위 구성 요소 추가/리디렉션 contentPane에 방법을 제거해야합니다

설명 :
, AWT 프로그래밍

달리 JFrame/JDialg/JWindow/JApplet/JInternalFrame은하지 않습니다 Component을 추가 할 수있게하려면 JRootPane에 대해 알아보고 어린이를 추가해야합니다. Component s입니다. 이는 새로운 개발자에게 불필요한 혼동을줍니다.

5.0 이전 버전에서는 Component을 추가하거나 제거하려고 시도했을 때 예외가 발생합니다. 5.0에서는 예외가 발생하지 않고 Component이 콘텐츠 창에서 추가되거나 제거됩니다. 이로서 JFrame, JDialog, JWindow, JAppletJInternalFrame의 javadoc에 몇 가지 수정 내용이 이됩니다. 이 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 + –

+0

매우 도움이됩니다. 감사합니다. – Alanmars