Java 如何使用元素的中心在 BoxLayout 中居中元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2560784/
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 to center elements in the BoxLayout using center of the element?
提问by Roman
I use outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
and then I add elements (for example JLabels, JButtons) to the outputPanel
. For example: outputPanel.add(submitButton);
.
我使用outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
然后将元素(例如 JLabels、JButtons)添加到outputPanel
. 例如:outputPanel.add(submitButton);
。
I see that all added elements are "centered". It is good, because I do want my elements to be in the center. When I write "center" I mean "equal distance from left and right". But the problem is that the left part of the element is put into the center. And I want to have center of elements to be put into the center. How can I get this behavior?
我看到所有添加的元素都“居中”。这很好,因为我确实希望我的元素位于中心。当我写“中心”时,我的意思是“左右距离相等”。但问题是元素的左侧部分被放入了中心。我希望将元素的中心放入中心。我怎样才能得到这种行为?
采纳答案by Roman
The problem can be solved by using myLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
. It works with JLabel
, JButton
and JRadioButton
.
问题可以通过使用来解决myLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
。它适用于JLabel
,JButton
和JRadioButton
。
回答by AdamK
So far the best method I've encountered that works with everytype of component:
1. Create a new JPanel:
到目前为止,我遇到的适用于所有类型组件的最佳方法:
1. 创建一个新的JPanel:
JPanel helperPanel = new JPanel();
2. Add the component (in this example submitButton
) you wish to center horizontally to the JPanel :
helperPanel.add(submitButton);
3. Add the panel to your original panel (the one with the BoxLayout):
outerPanel.add(helperPanel);
That's it!
You could also set a maximum size on the helperPanel
if you don't want the BoxLayout of the outerPanel
to expand it.
If you're wondering why this works: the implicit layout manager of a JPanel is FlowLayout, which centers your elements automatically.
JPanel helperPanel = new JPanel();
2. 将submitButton
您希望水平居中的组件(在本例中)helperPanel.add(submitButton);
添加到 JPanel :
3. 将面板添加到原始面板(带有 BoxLayout 的面板):
outerPanel.add(helperPanel);
就是这样!如果您不希望 的 BoxLayout展开它,您还可以在 上设置最大大小。
如果您想知道为什么会这样:JPanel 的隐式布局管理器是 FlowLayout,它会自动将您的元素居中。helperPanel
outerPanel