中心JButton在BorderLayout中

时间:2014-07-16 06:51:03

标签: java swing layout alignment border-layout

我正在尝试将我的按钮与CENTER对齐,但不知何故它不起作用。

如您所见,我尝试使用

newGameBtn.setHorizontalAlignment(JLabel.CENTER);

但不知怎的,布局忽略了它。

这是我的类(BaseView继承自JPanel):

import javax.swing.*;
import java.awt.*;

public class MenueView extends BaseView
{
    private JPanel _titlePanel = new JPanel();
    private JPanel _menuItemsPanel = new JPanel();

    private JLabel _title = new JLabel("Wer wird Millionär?");
    private JButton _newGameBtn = new JButton("Neues Spiel");
    private JButton _highscoreBtn = new JButton("Highscore");
    private JButton _quitBtn = new JButton("Beenden");

    public void InitializeComponents()
    {
        this.setLayout(new BorderLayout());

        _titlePanel.add(_title);

        _menuItemsPanel.setLayout(new BoxLayout(_menuItemsPanel, BoxLayout.Y_AXIS));
        _menuItemsPanel.add(_newGameBtn);
        _newGameBtn.setHorizontalAlignment(JLabel.CENTER);
        _menuItemsPanel.add(_highscoreBtn);
        _menuItemsPanel.add(_quitBtn);

        this.add(_titlePanel, BorderLayout.NORTH);
        this.add(_menuItemsPanel, BorderLayout.CENTER);
    }

    public MenueView(IConductor conductor)
    {
        super(conductor);
        InitializeComponents();
    }
}

是因为我使用了borderlayout吗?

感谢您的帮助

Alignment Issue

1 个答案:

答案 0 :(得分:0)

尝试将JBUttons添加到BorderLayout的Center-box中的gridlayout,如下所示:

gridlayout.add(_newGameBtn);
gridlayout.add(_highscoreBtn);
gridlayout.add(_quitBtn);

borderlayout.add(gridlayout, BorderLayout.CENTER);
panel.setLayout(borderlayout);

来源:  How to centre the Buttons in my JFrame?