views:

354

answers:

1

If I set a layout on a JFrame with setLayout and then retrieve it with getLayout then I get a different LayoutManager. What is going on here??

public class Lay {
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                java.awt.Container container =
                    new javax.swing.JFrame();
                    //new javax.swing.JPanel();
                java.awt.LayoutManager layout =
                    new java.awt.GridLayout();
                container.setLayout(layout);
                layout = container.getLayout();
                System.err.println(layout);
            }
        });
    }
}

Gives

java.awt.BorderLayout[hgap=0,vgap=0]

but if I replace JFrame with JPanel I get

java.awt.GridLayout[hgap=0,vgap=0,rows=1,cols=0]
+9  A: 

From the Java API for JFrame:

public void setLayout(LayoutManager manager)

Sets the LayoutManager. Overridden to conditionally forward the call to the contentPane. Refer to RootPaneContainer for more information.

And from the RootPaneContainer page:

This interface serves as a marker for Swing GUI builders that need to treat components like JFrame, that contain a single JRootPane, specially. For convenience JFrame, JDialog, JWindow, JApplet and JInternalFrame, by default, forward, by default, all calls to the add, remove and setLayout methods, to the contentPane. This means you can call:

rootPaneContainer.add(component);

instead of:

rootPaneContainer.getContentPane().add(component);

A JRootPane is a common component that all the heavyweight components use to appear like a native OS window. It handles the menu bar, close/minimize/maximize buttons, etc. JFrame tries to hide the fact that JRootPane does the real work from you, but in this case it just made things more confusing.

John Kugelman
Second ahead of me. Well done sir!
basszero
For the rationale behind the getContentPane stuff, Hans Muller explains: http://weblogs.java.net/blog/hansmuller/archive/2005/11/jframeadd_conte.html
McDowell
in other words: setLayout() is overriden in JFrame, while getLayout() is not...
Carlos Heuberger