1

为什么在将 JFrame 的布局设置为 BoxLayout 时,我必须使用getContentPane()而不是这个关键字作为 BoxLayout 的参数参数。为了给 JPanel 一个 BoxLayout,我必须使用作为参数。

我认为这是因为 JFrame 有几个层或部分,它们是玻璃窗格、分层窗格、内容窗格和菜单栏。所以this关键字指的是 JFrame,但它不是指我们想要配置布局管理器的内容窗格。这就是我们调用 getContentPane() 的原因。我读到 JFrame 的内容窗格实际上是一个 JPanel。

总结一下:BoxLayout 的目标参数接受 JPanel 但不接受 JFrame,但 JFrame 的内容窗格是 JPanel。

class MyFrame1 extends JFrame {
    public MyFrame1() {    
        // This line does not work, why? 
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); 
    }
}

class MyFrame2 extends JFrame {
    public MyFrame2() {    
        // This line works
        setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
    }
}

class MyPanel extends JPanel {
    public MyPanel() {
        // JPanel uses "this" keyword
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    }
}

JPanel 是否有多个像 JFrame 一样的窗格?我必须使用 getContentPane() 的实际原因是什么?

当编译器说不能共享 BoxLayout 时,是否意味着不能在组成 JFrame 的多个窗格之间共享 BoxLayout?

4

1 回答 1

1

AJFrame是 a Container,但它不是Container “需要布局的”。相反,Container返回的 ,getContentPane()是可以使用 的实例的BoxLayout。或者考虑下面的变体,“使用对象作为其布局管理器Box的轻量级容器”。BoxLayout

Box b = Box.createVerticalBox();
b.add(new JLabel("Test"));
f.setContentPane(b);

经测试:

import java.awt.EventQueue;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;

/** @see http://stackoverflow.com/a/23159430/230513 */
public class Test {

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Box b = Box.createVerticalBox();
        b.add(new JLabel("Test"));
        f.setContentPane(b);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Test().display();
            }
        });
    }
}
于 2014-04-18T17:52:39.993 回答