java 如何仅为 FlowLayout 的一部分设置水平间隙?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6507695/
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
How do I set the horizontal gap for just one part of a FlowLayout?
提问by Grammin
I have a flow layout with three buttons, between the first and second buttons I would like a horizontal gap of 30 and between the second and third buttons I would like a horizontal gap of 10. I tried this:
我有一个包含三个按钮的流布局,在第一个和第二个按钮之间我想要一个 30 的水平间隙,在第二个和第三个按钮之间我想要一个 10 的水平间隙。我试过这个:
Jpanel panel = new JPanel(new FlowLayout());
JButton button1 = new Button("1");
JButton button2 = new Button("2");
JButton button3 = new Button("3");
panel.add(button1);
((FlowLayout)panel.getLayout()).setHgap(30);
panel.add(button2);
((FlowLayout)panel.getLayout()).setHgap(10);
panel.add(button3);
But this changes all of the Horizontal gaps to 10.
但这会将所有水平间隙更改为 10。
Any ideas would be appreciated, Thanks.
任何想法将不胜感激,谢谢。
回答by Penkov Vladimir
try to use Box.createHorizontalStrut
尝试使用 Box.createHorizontalStrut
panel.add(button1);
panel.add(Box.createHorizontalStrut(30));
panel.add(button2);
Box.createHorizontalStrut(10);
panel.add(button3);
回答by Andrew Thompson
Add an EmptyBorder
to the 2nd button, with the additional pixels in the second parameter (left
):
EmptyBorder
向第二个按钮添加,并在第二个参数 ( left
) 中添加额外的像素:
button2.setBorder(new EmptyBorder(0, 20, 0, 0));
回答by meverett
You could try MigLayout:
你可以试试 MigLayout:
Jpanel panel = new JPanel(new MigLayout());
panel.add(new Button("1"), "gap right 30");
panel.add(new Button("2"), "gap right 10");
panel.add(new Button("3"));
回答by PrimosK
The alternative solution would be to use a createRigidArea(...)
which creates an invisible component that's always the specified size. Such component can then be used as a spacer:
另一种解决方案是使用 acreateRigidArea(...)
来创建一个始终具有指定大小的不可见组件。然后可以将此类组件用作垫片:
panel.add(button1);
panel.add(Box.createRigidArea(new Dimension(30, 0)));
panel.add(button2);
panel.add(Box.createRigidArea(new Dimension(10, 0)));
panel.add(button3);