Rom*_*man 27 java layout user-interface swing center
我使用outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));然后我添加元素(例如JLabels,JButtons)outputPanel.例如:outputPanel.add(submitButton);.
我看到所有添加的元素都是"居中"的.这很好,因为我确实希望我的元素在中心.当我写"中心"时,我指的是"左右相等的距离".但问题是元素的左侧部分被放入中心.我希望将元素的中心放入中心.我怎么能得到这种行为?
Rom*_*man 45
问题可以通过使用来解决myLabel.setAlignmentX(Component.CENTER_ALIGNMENT);.它适用于JLabel,JButton和JRadioButton.
到目前为止,我遇到的适用于每种类型组件的最佳方法:
1. 创建一个新的JPanel:
JPanel helperPanel = new JPanel();
2. 将您希望水平居中的组件(在本示例中submitButton)添加到 JPanel:
helperPanel.add(submitButton);
3. 将面板添加到原始面板(带有 BoxLayout 的面板):
outerPanel.add(helperPanel);
就是这样!如果您不希望 BoxLayout 展开,您还可以设置最大尺寸。
如果您想知道为什么会这样:JPanel 的隐式布局管理器是 FlowLayout,它会自动将元素居中。helperPanelouterPanel