【问题标题】:LayoutManager of JFrame's contentPaneJFrame 的 contentPane 的 LayoutManager
【发布时间】:2012-07-08 12:24:42
【问题描述】:

这里提到:Adding Components to the Content Pane,

默认内容窗格是一个简单的中间容器, 继承自 JComponent,并使用 BorderLayout 作为其布局 经理。

这是一个证明:

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

但是,你能解释一下下面代码的输出吗?

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());

输出:

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

【问题讨论】:

  • 如有疑问,请阅读源代码:-)

标签: java swing jframe border-layout contentpane


【解决方案1】:

这解释了你的结果:

 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;
    }

创建内容窗格的方法会创建一个继承自 BorderLayout 的匿名内部类。 因此对 instanceof 的测试将返回 true 但它是另一个类,因此类名不同。

【讨论】:

  • 另外,类名中的$ 是一个内部类在起作用的迹象。在这种情况下,内部类是匿名的,因此您看到的是 $1 而不是实际名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多