如何在 BoxLayout 中居中 JLabel 和 JButton

ven*_*uil 3 java swing awt layout-manager 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();
Run Code Online (Sandbox Code Playgroud)

方法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());
Run Code Online (Sandbox Code Playgroud)

方法addButton()

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

    add(button);
}
Run Code Online (Sandbox Code Playgroud)

addLabel()

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

    add(label);
}
Run Code Online (Sandbox Code Playgroud)

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

rdo*_*nuk 5

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

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

编辑:

你的第二个问题很奇怪。我不知道为什么会发生这种情况,但我认为为按钮创建第二个面板将解决您的问题。

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

super();

//set size

setLayout(new BorderLayout());

addButtons();
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

createButton()方法

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

    return button;
}
Run Code Online (Sandbox Code Playgroud)

addLabel()方法

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