BorderLayout中心命令不会居中

Ric*_*cco 2 java layout swing

我试图JButton在a的中心将两个s 放在彼此旁边,JFrameJFrame重新调整大小时,不会重新调整按钮的大小.

为此,我将两个按钮放在带有a的面板中,FlowLayout然后放在带有中心的面板中BorderLayout.

但是,以下代码不会在中心显示所选面板BorderLayout.

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class test extends JFrame {

    private JPanel panel1 = new JPanel();
    private JPanel panel2 = new JPanel();
    private JButton button1 = new JButton("one");
    private JButton button2 = new JButton("two");

    public test() {
        panel1.setLayout(new FlowLayout());
        panel1.add(button1);
        panel1.add(button2);

        panel2.setLayout(new BorderLayout());
        panel2.add(panel1, BorderLayout.CENTER);

        this.add(panel2);
    }

    public static void main(String[] args) {
        test frame = new test();
        frame.setVisible(true);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
Run Code Online (Sandbox Code Playgroud)

ada*_*ost 5

设置GridBagLayoutpanel1.

 panel1.setLayout(new GridBagLayout());
Run Code Online (Sandbox Code Playgroud)

编辑:

@trashgod:我必须弄清楚默认约束是如何做到的.

因为字段GridBagLayout.defaultConstraints:

此字段包含一个包含默认值的gridbag约束实例,因此如果某个组件没有与之关联的gridbag约束,则将为该组件分配defaultConstraints的副本.

在通常的实践中,必须创建GridBagConstraints对象并设置字段以指定每个对象的约束.

引用教程:

设置组件约束的首选方法是使用Container.add变量,并将其传递给GridBagConstraints对象