38

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

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

4

2 回答 2

54

问题可以通过使用来解决myLabel.setAlignmentX(Component.CENTER_ALIGNMENT);。它适用于JLabel和。JButtonJRadioButton

于 2010-04-01T14:52:51.727 回答
4

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

JPanel helperPanel = new JPanel();

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

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

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

于 2017-12-10T19:35:29.087 回答