【问题标题】:How to center elements in the BoxLayout using center of the element?如何使用元素的中心将 BoxLayout 中的元素居中?
【发布时间】:2011-02-03 09:13:26
【问题描述】:

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

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

【问题讨论】:

  • 我遇到了类似的问题,发现使用 BoxLayout 代替 FlowLayout 效果更好,并且更容易在其中居中对齐对象。

标签: java user-interface swing layout center


【解决方案1】:

这个问题可以通过myLabel.setAlignmentX(Component.CENTER_ALIGNMENT);来解决。它适用于JLabelJButtonJRadioButton

【讨论】:

  • 我试过了,发现所有项目都必须将 setAlignmentX(Component.CENTER_ALIGNMENT) 应用于相同的 CENTER_ALIGNMENT 值。仅将其应用于一个 JButton 并没有帮助。 setHorizo​​ntalAlignment(SwingConstants.CENTER) 也根本没有帮助。希望这对您有所帮助。
  • 虽然它可以单独与 JLabelJComboboxes 一起使用,但在组合它们时它不起作用。
【解决方案2】:

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

JPanel helperPanel = new JPanel();

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

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

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

【讨论】:

  • 我会用new Borderlayout() 实例化helperPanel,否则在使用最大尺寸技巧时组件将被切断。
猜你喜欢
  • 2014-07-20
  • 2020-01-29
  • 2022-08-21
  • 2017-08-25
  • 2010-11-15
  • 1970-01-01
  • 2011-07-31
  • 2021-06-11
  • 2021-02-09
相关资源
最近更新 更多