如何设置垂直排列的元素之间的距离?

我有这样的代码:

JPanel myPanel = new JPanel(); myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS)); JButton button = new JButton("My Button"); JLabel label = new JLabel("My label!!!!!!!!!!!"); myPanel.add(button); myPanel.add(label); 

通过这种方式,我获得了它们之间没有距离的元素。 我的意思是,“顶部”元素总是触及“底部”元素。 我该怎么改变它? 我想在我的元素之间有一些分离?

我想在我的元素之间添加一些“中间”JPanel(有一些大小)。 但我不认为这是一种获得理想效果的优雅方式。 有人可以帮助我吗?

  JPanel myPanel = new JPanel(); myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS)); JButton button = new JButton("My Button"); JLabel label = new JLabel("My label!!!!!!!!!!!"); myPanel.add(button); myPanel.add(Box.createVerticalStrut(20)); myPanel.add(label); 

这将是一种方式。

如果您肯定打算使用BoxLayout来布局面板,那么您应该看看如何使用BoxLayout Sun Learning Trail,特别是使用Invisible Components作为填充程序部分。 简而言之,使用BoxLayout您可以创建特殊的不可见组件,充当其他组件之间的间隔符:

 container.add(firstComponent); container.add(Box.createRigidArea(new Dimension(5,0))); container.add(secondComponent); 

您可能需要考虑使用GridLayout而不是BoxLayout,它具有Hgap和Vgap属性,可让您指定组件之间的常量分隔。

 GridLayout layout = new GridLayout(2, 1); layout.setVgap(10); myPanel.setLayout(layout); myPanel.add(button); myPanel.add(label); 

使用Box类作为隐形填充元素。 这就是Sun建议您这样做的方式。

BoxLayout教程 。