当在 Jlabel 之前添加 Jlabel 时如何阻止 JButton 改变位置

how to stop JButton from changing position when a Jlabel is added before it

我有一个最初为空白的 JLabel (seriesInformationLabel)。旁边有一个Jbutton(copyButton)。问题是每次 JLabel 加载文本值时,JButton 都会向右移动。如何阻止此 JButton 移动?

private void init() {
    super.initializeLayout();
    this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    Box buttonPanel = Box.createHorizontalBox();
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
    buttonPanel.setLayout(null);
    copyButton = new JButton(Utilities.getString("COPY"));
    copyButton.setActionCommand(COPY);
    copyButton.setEnabled(false);

    seriesInformationLabel = new JLabel();
    seriesInformationLabel.setAlignmentY(CENTER_ALIGNMENT);
    seriesInformationLabel.setName(this.getClass().getSimpleName() + "_seriesInformationLabel");

    buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
    buttonPanel.add(seriesInformationLabel);
    buttonPanel.add(Box.createHorizontalGlue());
    buttonPanel.add(copyButton);
    buttonPanel.add(Box.createHorizontalGlue());
  }
buttonPanel.add(seriesInformationLabel);
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(copyButton);
buttonPanel.add(Box.createHorizontalGlue());

免费 space 随着标签文本的变化而变化。

这意味着 "glue" 可用的 space 将在导致按钮移动的两个胶水组件之间平均变化。

如果您不想让按钮移动,那么您需要删除第二个 "glue" 组件:

buttonPanel.add(seriesInformationLabel);
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(copyButton);
//buttonPanel.add(Box.createHorizontalGlue());

如果您不想让按钮完全位于面板的右边缘,也许可以添加另一个刚性区域。