如何使用元素的中心将BoxLayout中的元素居中?

时间:2010-04-01 13:49:07

标签: java user-interface swing layout center

我使用outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));然后我将元素(例如JLabel,JButtons)添加到outputPanel。例如:outputPanel.add(submitButton);

我看到所有添加的元素都是“居中”的。这很好,因为我确实希望我的元素在中心。当我写“中心”时,我指的是“左右相等的距离”。但问题是元素的左侧部分被放入中心。我希望将元素的中心放入中心。我怎么能得到这种行为?

2 个答案:

答案 0 :(得分:45)

使用myLabel.setAlignmentX(Component.CENTER_ALIGNMENT);可以解决问题。它适用于JLabelJButtonJRadioButton

答案 1 :(得分:0)

到目前为止,我遇到的最佳方法适用于每种类型的组件:
1.创建一个新的 JPanel

JPanel helperPanel = new JPanel();

2.将您希望水平居中的组件(在此示例中为submitButton)添加到JPanel:
helperPanel.add(submitButton);

3.将面板添加到原始面板(带有BoxLayout的面板): outerPanel.add(helperPanel);

那就是它! 如果您不希望helperPanel的BoxLayout展开它,您还可以在outerPanel上设置最大尺寸。 如果您想知道为什么会这样:JPanel的隐式布局管理器是FlowLayout,它会自动使您的元素居中。

相关问题