Eng.Fouad
Eng.Fouad

Reputation: 117597

LayoutManager of JFrame's contentPane

As mentioned here: Adding Components to the Content Pane,

The default content pane is a simple intermediate container that inherits from JComponent, and that uses a BorderLayout as its layout manager.

and here is a proof:

JFrame frame = new JFrame();
LayoutManager m = frame.getContentPane().getLayout();
System.out.println(m instanceof BorderLayout); // prints true

However, can you explain the output of the following code?

JFrame frame = new JFrame();

LayoutManager m = frame.getContentPane().getLayout();
System.out.println(m);
System.out.println(m.getClass().getName());

LayoutManager m2 = new BorderLayout();
System.out.println(m2);
System.out.println(m2.getClass().getName());

OUTPUT:

javax.swing.JRootPane$1[hgap=0,vgap=0]
javax.swing.JRootPane$1
java.awt.BorderLayout[hgap=0,vgap=0]
java.awt.BorderLayout

Upvotes: 4

Views: 2359

Answers (1)

Peter
Peter

Reputation: 5798

this explains your result:

 protected Container createContentPane() {
        JComponent c = new JPanel();
        c.setName(this.getName()+".contentPane");
        c.setLayout(new BorderLayout() {
            /* This BorderLayout subclass maps a null constraint to CENTER.
             * Although the reference BorderLayout also does this, some VMs
             * throw an IllegalArgumentException.
             */
            public void addLayoutComponent(Component comp, Object constraints) {
                if (constraints == null) {
                    constraints = BorderLayout.CENTER;
                }
                super.addLayoutComponent(comp, constraints);
            }
        });
        return c;
    }

The method creating the contentpane creates an anonymous inner class that inherits from BorderLayout. So testing on instanceof will return true but its another class so the class name is different.

Upvotes: 5

Related Questions