2010-04-01 137 views
10

我有这样的代码:如何设置垂直排列的元素之间的距离?

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(有一些大小)。但我不认为这是一种获得理想效果的优雅方式。有人可以帮助我吗?

回答

13
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); 

将是一种做法。

1

使用Box类作为不可见的填充元素。 Sun推荐你这样做。

BoxLayout tutorial

2

您可能想要考虑GridLayout而不是BoxLayout,它具有Hgap和Vgap属性,可以指定组件之间的常量分离。

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

如果你确实打算使用BoxLayout布局的面板,那么你应该看看How to Use BoxLayout太阳学习资源,特别是Using Invisible Components as Filler部分。总之,随着BoxLayout您可以创建作为您的其他组件之间的间隔特别无形成分:

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

在这种情况下,你也可以使用Box.createVerticalStrut(5)。还有一个补充性的Box.createHorizo​​ntalStrut(int)。当其中一个维度为零时,我更喜欢这些。 – 2010-04-01 15:16:05

相关问题