BorderLayout设计错误

时间:2015-11-03 04:48:34

标签: java swing jbutton border-layout

我有一些代码如下:

public static void main(String[] args) {
    JFrame f = new BorderTest();
    JPanel p = new JPanel();

    p.setLayout(new BorderLayout());
    p.add(new JButton("West"), "West");
    p.add(new JButton("East"), "East");
    p.add(new JButton("North"), "North");
    p.add(new JButton("Center"), "Center");
    p.add(new JButton("South"), "South");

    Container c = f.getContentPane();
    c.add(p);
    f.pack();
    f.setVisible(true);
}

产生:

enter image description here

我如何修改我的代码以使其按钮北和南的宽度与中心相同,西和东向垂直扩展以填充空间?

感谢。

1 个答案:

答案 0 :(得分:5)

使用BorderLayout将“North”,“South”和“Center”组件添加到另一个容器,将此容器添加到主容器的CENTER位置

Layout

JPanel p = new JPanel(new BorderLayout());

    JPanel middle = new JPanel(new BorderLayout());
    middle.add(new JButton("NORTH"), BorderLayout.NORTH);
    middle.add(new JButton("CENTER"), BorderLayout.CENTER);
    middle.add(new JButton("SOUTH"), BorderLayout.SOUTH);

    p.add(middle);
    p.add(new JButton("EAST"), BorderLayout.EAST);
    p.add(new JButton("WEST"), BorderLayout.WEST);