BoxLayout可以很好地在组件之间分配空间
Box.createVerticalGlue()。本示例使用
Box.createVerticalStrut(),顶部和底部。
如何使用BoxLayout:使用不可见的组件作为填充器
中介绍了间隔器。
附录:
BoxTest2是一种变体,用于
BoxLayout创建固定大小的边缘面板和垂直胶水,以更均匀地分布空间。
Box.Filler也可以用于控制“剩余”垂直空间。
public class BoxTest2 { private static final int WIDE = 480; private static final int HIGH = WIDE / 8; private static final int ROWS = 5; private static final Box center = new Box(BoxLayout.Y_AXIS); public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { Jframe f = new Jframe(); f.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); center.setOpaque(true); center.setBackground(Color.lightGray); center.add(Box.createVerticalGlue()); center.add(new EdgePanel()); for (int i = 0; i < ROWS; i++) { center.add(new BoxPanel()); } center.add(new EdgePanel()); center.add(Box.createVerticalGlue()); f.add(center, BorderLayout.CENTER); f.pack(); f.setVisible(true); } }); } private static class EdgePanel extends JPanel { public EdgePanel() { Dimension d = new Dimension(WIDE, 2 * HIGH / 3); setPreferredSize(d); setBackground(Color.red.darker()); } } private static class BoxPanel extends JPanel { public BoxPanel() { setPreferredSize(new Dimension(WIDE, HIGH)); setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.red)); setBackground(Color.darkGray); } }}


