【问题标题】:How can I set distance between elements ordered vertically?如何设置垂直排序的元素之间的距离?
【发布时间】:2011-02-03 09:57:43
【问题描述】:

我有这样的代码:

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

【问题讨论】:

    标签: java swing user-interface


    【解决方案1】:

    使用Box 类作为不可见的填充元素。 Sun 建议您这样做。

    BoxLayout tutorial.

    【讨论】:

      【解决方案2】:
          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);
      

      将是这样做的一种方式。

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

          如果您确实打算使用BoxLayout 来布置您的面板,那么您应该查看How to Use BoxLayout Sun Learning Trail,特别是Using Invisible Components as Filler 部分。简而言之,使用BoxLayout,您可以创建特殊的隐形组件,充当其他组件之间的间隔:

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

          【讨论】:

          • 在这种情况下,您还可以使用 Box.createVerticalStrut(5)。还有一个互补的 Box.createHorizo​​ntalStrut(int) 。当其中一个维度为零时,我更喜欢这些。