我有一些代码如下:
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);
}
产生:
我如何修改我的代码以使其按钮北和南的宽度与中心相同,西和东向垂直扩展以填充空间?
感谢。
答案 0 :(得分:5)
使用BorderLayout
将“North”,“South”和“Center”组件添加到另一个容器,将此容器添加到主容器的CENTER
位置
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);