如何在BoxLayout中居中JLabel和JButton

3
我想创建一个简单菜单,包含不同难度级别。

Screen shot

下面几行代码是构造函数。
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 中的文本会变为简单的“当前级别 EASY”。然后,JButtons 会向右移动许多像素,我不知道为什么。
1个回答

5

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() method

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

1
好的,它正在工作,但是当我改变级别(和JLabel中的文本)时,我的按钮会向右移动几个像素。 - ventaquil
setAlignmentX 对我也起了作用。 - Michal - wereda-net

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接