Java 如何在BoxLayout中居中放置JLabel和JButton

Java 如何在BoxLayout中居中放置JLabel和JButton,java,swing,awt,layout-manager,boxlayout,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(); 方法addButtons

我想创建简单的菜单与困难的水平

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

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());
addLabel()


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

公共JLabel(字符串文本,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);
addLabel()
方法

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

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

好的,它正在工作,但当我更改级别(以及
JLabel
中的文本)时,我的按钮会将一些像素移动到右边缘。setAlignmentX也为我完成了这项工作
private JButton createButton(String text)
{
    JButton button = new JButton(text);
    button.setAlignmentX(JButton.CENTER_ALIGNMENT);
    button.setFocusable(false);

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