Why JFrame initially requires getContentPane () to add components

I know that from Java 1.5 you can add a component to a JFrame as follows:

myFrame.add (MyButton);

instead:

myFrame.getContentPane () add (MyButton) ;.

Why is this not always the case?

+8
java swing jframe
source share
2 answers

As stated in the JFrame API , both do the same: add the component to the contentPane. This is just recently (maybe Java 1.5?) Swing added a sugar / convenience syntax method so you can make this call directly on a JFrame (or any other Swing top-level container), but you still add it to the contentPane. The same goes for remove(...) and setLayout(...) This becomes too clear if you are trying to set the background color of the JFrame through myJFrame.setBackground(Color.green); and nothing happens. It is for this reason that I am not too happy with this change. This is also because I have to be an old idol.

+9
source share

4753342: The top-level swing component should redirect add / remove methods in ContentPane

Description:

Unlike AWT programming, JFrame / JDialg / JWindow / JApplet / JInternalFrame do not allow you to add Component , instead you should learn about JRootPane and add Component children to it. This adds unnecessary confusion to new developers.

Prior to 5.0, attempting to add or remove Component from one of this upper level Component will throw an exception. In 5.0, an exception will not be thrown; instead, Component will be added or removed from the content area. This has led to several revisions to javadoc JFrame , JDialog , JWindow , JApplet and JInternalFrame . This has been summarized in the RootPaneContainer's 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. 

In addition, an error is related here:

+7
source share

All Articles