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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2561305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:17:08  来源:igfitidea点击:

How can I set distance between elements ordered vertically?

javaswinguser-interface

提问by Roman

I have code like that:

我有这样的代码:

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

In this way I get elements with no distance between them. I mean, the "top" elements always touches the "bottom" element. How can I change it? I would like to have some separation between my elements?

通过这种方式,我得到了它们之间没有距离的元素。我的意思是,“顶部”元素总是接触“底部”元素。我怎样才能改变它?我想在我的元素之间进行一些分离?

I think about adding some "intermediate" JPanel (with some size) between my elements. But I do not think it is an elegant way to get the desired effect. Can somebody, please, help me with that?

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

采纳答案by Kannan Ekanath

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

will be one way of doing it.

将是一种方法。

回答by Stefan Kendall

Use the Boxclass as an invisible filler element. This is how Sun recommends you do it.

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

BoxLayout tutorial.

BoxLayout 教程

回答by M. Jessup

You may want to consider GridLayout instead of BoxLayout, it has attributes Hgap and Vgap that let you specify a constant seperation between components.

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

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

回答by RTBarnard

If you're definitely intending to use BoxLayoutto layout your panel, then you should have a look at the How to Use BoxLayoutSun Learning Trail, specifically the Using Invisible Components as Fillersection. In short, with BoxLayoutyou can create special invisible components that act as spacers between your other components:

如果您确实打算使用BoxLayout布局面板,那么您应该查看如何使用 BoxLayoutSun 学习资源,特别是使用隐形组件作为填充物部分。简而言之,BoxLayout您可以创建特殊的隐形组件,作为其他组件之间的间隔物:

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