java - 如何在 BoxLayout 中将 JLabel 和 JButton 居中

标签 java swing awt layout-manager boxlayout

我想创建具有难度级别的简单菜单

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 向右移动了很多像素,我不知道为什么。

最佳答案

public JLabel(String text, int horizo​​ntalAlignment) 中的第二个参数用于确定标签的文本位置。您需要通过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);
}

关于java - 如何在 BoxLayout 中将 JLabel 和 JButton 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36971259/

相关文章:

java - Calibri 字体在 <html> 文本中移动到组件的底部

JAVA数组输出

java - Maven依赖版本不一样

java - Sprite 在特定的 JPanel 上生成

java - 如何使 JFrame 背景和 JPanel 透明,只显示图像

Java 从我的程序中获取奇怪的文本作为输出

java - 我可以将参数从布局 XML 传递到 MainActivity 中的方法吗?

java - Android导入项目失败

java - 在哪里存储一致的应用程序属性?

java - 如何通过将Panel设置为Parent来打开FileDialog?