Question

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
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top