java - JFrame 的 contentPane 的 LayoutManager

标签 java swing jframe border-layout contentpane

如此处所述: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.

这是一个证明:

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

最佳答案

这解释了你的结果:

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

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

关于java - JFrame 的 contentPane 的 LayoutManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11389387/

相关文章:

java - JavaFX 中现有 java bean 的异步绑定(bind)

java - 在 jenkinsci/blueocean 容器内找不到 Jenkins conf 文件

Java - 多个组件之上(GUI)

java - AffineTransform 翻译不同的图形对象

java - JFrame 打开为空

java - 在框架外显示元素

java - 如何在 Spring Controller 中检索 FORM/POST 参数?

java - JAX-RS/ Jersey : How can I "inherit" @Provider fields?

java - 如何在 JTextArea 列表中浏览此代码的结果?

java - JFrame 生命周期