使JButton自适应JPanel大小

3

我想让我的按钮填满面板的宽度。这是我的代码,创建了一个按钮和一个面板,然后将按钮添加到面板上。

buttonPane = makeButtonPanel();
button = makeButton("Hello"); 
button2 = makeButton("World");
buttonPane.add(button);
buttonPane.add(button2);

private JButton makeButton(String msg){
    JButton button = new JButton(msg);
    button.setAlignmentX(Component.CENTER_ALIGNMENT); 
    return button;
}

private JPanel makeButtonPanel(){
    JPanel btnPanel = new JPanel();
    btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.Y_AXIS));
    btnPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    return btnPanel;
}

这是我得到的输出...

在此输入图像描述

1个回答

4

对于多个按钮,宽度尽可能自适应的情况,请在北部位置放置一个容器,而不是单个按钮,该容器包含多个JButton。该容器可能应该是一个具有GridLayout, 1列和与按钮数量相等的行数的JPanel。


可以运行!但是如果我尝试在下面添加另一个按钮,它会替换原来位于边框布局北部的那个按钮。我应该更清楚地表明我将在面板内添加多个按钮。 - IndyS
在北侧位置放置不只是一个 JButton,而是另一个包含更多 JButtons 的容器。听起来你想要在一个带有 x 行的 JPanel 中拥有多个 JButtons (其中 x 是你拥有的按钮数量),以及 1 列。然后将该带有 GridLayout 的 JPanel 放置在所讨论答案中的原始 JPanel 的 North 位置。GridLayout(而不是 GridBagLayout)希望其组件填满尽可能多的空间,并为每个组件提供相等的空间,因此它应该允许其中的按钮完全拉伸到左侧和右侧。 - NESPowerGlove

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接