BorderLayout中心命令不会居中

时间:2011-11-26 05:39:47

标签: java swing layout

我正在尝试将两个JButton彼此相邻放在JFrame的中心,当JFrame重新调整大小时,不会重新调整按钮的大小

为此,我将两个按钮放在一个带有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);
    }
}

3 个答案:

答案 0 :(得分:5)

GridBagLayout设为panel1

 panel1.setLayout(new GridBagLayout());

编辑:

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

由于字段GridBagLayout.defaultConstraints

  

此字段包含一个包含默认值的gridbag约束实例   值,因此如果组件没有关联的gridbag约束   有了它,那么该组件将被分配一份   一个defaultConstraints。

在正常练习中,必须创建GridBagConstraints对象并设置字段以在每个对象上指定约束

引用tutorial

  

设置约束的首选方法   组件是使用Container.add变体,传递它   GridBagConstraints对象

答案 1 :(得分:3)

看起来不直观,但行为正确。

panel1被分配了尽可能多的屏幕空间,因为它是panel2内唯一的组件。 FlowLayout然后从可用空间的顶部开始放置组件,并且只有在填充了所有可用的水平空间后才将组件放下。因此,您可以在框架的顶部找到两个按钮。

您可以尝试使用Box代替:

public class test extends JFrame {

    private JComponent box = Box.createHorizontalBox();
    private JButton button1 = new JButton("one"); 
    private JButton button2 = new JButton("two"); 

    public test() {
        box.add(Box.createHorizontalGlue());
        box.add(button1);
        box.add(button2);
        box.add(Box.createHorizontalGlue());
        this.add(box);
    }

    ...
}

水平盒自动垂直对中组件,两个胶水组件占用任何额外的水平空间,使按钮位于盒子的中心。

答案 2 :(得分:0)

默认情况下JPanel使用FlowLayout,默认情况下FlowLayout使用居中对齐...这对我来说比去GridBagLayout甚至BoxLayout更容易。如果您不希望按钮在面板变得太小时“换行”,则可以设置最小尺寸。

package example;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FlowLO extends JFrame
{
    public static void main(String[] args)
    {
        FlowLO flowLO = new FlowLO();
        flowLO.go();
    }
    public void go()
    {
        JPanel centeredPanel = new JPanel();
        centeredPanel.add(new JButton("one"));
        centeredPanel.add(new JButton("two"));
        getContentPane().add(centeredPanel);
        pack();
        setVisible(true);
    }
}