如何在 BoxLayout 中将 JLabel 和 JButton 居中

How to center JLabel and JButton in BoxLayout

我想创建简单但关卡难的菜单

接下来几行代码是构造函数。

super();

setMinimumSize(new Dimension(600, 300));

setMaximumSize(new Dimension(600, 300));

setPreferredSize(new Dimension(600, 300));

setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

addButtons();

方法addButtons() 添加您可以在屏幕截图中看到的按钮:

add(Box.createVerticalGlue());

addLabel("<html>Current level <b>" + Game.instance()
                                         .getLevelString() +
         "</b></html>");

add(Box.createVerticalGlue());

addButton("Easy");

add(Box.createVerticalGlue());

addButton("Normal");

add(Box.createVerticalGlue());

addButton("Hard");

add(Box.createVerticalGlue());

addButton("Back");

add(Box.createVerticalGlue());

方法addButton()

private void addButton(String text)
{
    JButton button = new JButton(text);
    button.setAlignmentX(JButton.CENTER_ALIGNMENT);
    button.setFocusable(false);

    add(button);
}

addLabel()

private void addLabel(String text)
{
    JLabel label = new JLabel(text, JLabel.CENTER);

    add(label);
}

我不知道如何将所有元素居中对齐。这对我来说是个问题。另一个问题是,当我将 JLabel 上的困难级别文本更改为简单 'Current level EASY' 时。然后 JButtons 向右移动了很多像素,我不知道为什么。

public JLabel(String text, int horizontalAlignment)中的第二个参数用于确定标签的文本位置。您需要通过 setAlignmentX 方法设置 JLabel 组件的对齐方式。

private void addLabel(String text) {
    JLabel label = new JLabel(text, JLabel.CENTER);
    label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
    add(label);
}

编辑:

你的第二个问题很奇怪。我不知道为什么会这样,但我认为为按钮创建第二个面板可以解决您的问题。

在构造函数中使用边框布局:

super();

//set size

setLayout(new BorderLayout());

addButtons();

addButtons()方法:

//you can use empty border if you want add some insets to the top
//for example: setBorder(new EmptyBorder(5, 0, 0, 0));

addLabel("<html>Current level <b>" + Game.instance()
                                     .getLevelString() +
     "</b></html>");

JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.PAGE_AXIS));

buttonPanel.add(Box.createVerticalGlue());

buttonPanel.add(createButton("Easy"));

buttonPanel.add(Box.createVerticalGlue());

//Add all buttons

add(buttonPanel, BorderLayout.CENTER);

createButton()方法

private JButton createButton(String text)
{
    JButton button = new JButton(text);
    button.setAlignmentX(JButton.CENTER_ALIGNMENT);
    button.setFocusable(false);

    return button;
}

addLabel()方法

private void addLabel(String text)
{
    JLabel label = new JLabel(text, JLabel.CENTER);
    add(label, BorderLayout.NORTH);
}