簡體   English   中英

如何在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()添加您可以在screenshoot上看到的按鈕:

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 horizontalAlignment)中的第二個參數public JLabel(String text, int horizontalAlignment)用於確定標簽的文本位置。 您需要通過setAlignmentX方法設置JLabel組件的setAlignmentX

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM