【问题标题】:Center JButton's in BorderLayout在 BorderLayout 中居中 JButton
【发布时间】:2014-09-06 14:00:48
【问题描述】:

我正在尝试将我的按钮与 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.CENTER
  • JButton.CENTER 没有成功。此外,BorderLayout.CENTER 给了我一个构建错误。
  • JButton.CENTER 没有成功。此外,BorderLayout.CENTER 给了我一个构建错误。 == 为了获得更好的帮助,请尽快发布 SSCCE/MCVE,简短、可运行、可编译
  • 尝试使用 GridBagLayout 而不是 BoxLayout
  • 并阅读官方Oracle教程-如何使用BorderLayout,提示有5个区域......

标签: java swing layout alignment border-layout


【解决方案1】:

尝试将您的 JBUtton 添加到 BorderLayout 的中心框内的网格布局中,如下所示:

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?

【讨论】:

  • 是否可以在布局中添加布局?
  • @Jannik 布局已添加到面板中。我相信这里所谓的gridLayoutborderLayout实际上应该叫ratehrgridPanelborderPanel
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 2011-06-18
相关资源
最近更新 更多