以下是代码:
//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);
此代码生成以下窗口:
但这并不是我想要的。最右边的按钮边框未对齐。有没有办法以这种方式放置这些组件: