如何使用BoxLayout和FlowLayout对齐面板

时间:2016-04-25 16:02:23

标签: java layout-manager

以下是代码:

//Top-level container
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

//JPanel 1
JPanel p1 = new JPanel();
BoxLayout b1 = new BoxLayout(p1, BoxLayout.X_AXIS);
p1.setLayout(b1);
p1.add(new JButton("1"));
p1.add(Box.createHorizontalGlue());
p1.add(new JButton("1"));

//JPanel 2
JPanel p2 = new JPanel();
FlowLayout fl = new FlowLayout(FlowLayout.LEADING, 0, 0);
p2.setLayout(fl);
p2.add(new JButton("2"));
p2.add(new JButton("2"));
p2.add(new JButton("2"));
p2.add(new JButton("2"));
p2.add(new JButton("2"));


panel.add(p1);
panel.add(p2);

此代码生成以下窗口:

enter image description here

但这并不是我想要的。最右边的按钮边框未对齐。有没有办法以这种方式放置这些组件:

enter image description here

0 个答案:

没有答案