【问题标题】:Make JButton stretch to fit JPanel使 JButton 拉伸以适合 JPanel
【发布时间】:2014-04-07 17:13:48
【问题描述】:

我正在尝试让我的按钮填充面板的宽度,这是我的代码 制作一个按钮和一个面板,然后将按钮添加到面板中。

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

这是我得到的输出......

【问题讨论】:

    标签: java swing user-interface jpanel jbutton


    【解决方案1】:

    按钮如何适应它的容器取决于容器的布局。如果你想让它伸展你可以让按钮面板有一个 BorderLayout 并将按钮添加到北位置,或者使用任何其他布局类型,其组件试图尽可能多地占据空间(BorderLayout with north 是只是一个例子)。

    对于尽可能多地横向拉伸的多个按钮,请将容器放置在 North 位置,而不是单个按钮,该容器包含多个 JButton。该容器可能应该是一个带有 GridLayout、1 列、与按钮一样多的行的 JPanel。

    【讨论】:

    • 行得通!但是如果我尝试在下面添加另一个按钮,它会替换原来位于边框布局北部的按钮。我应该更清楚我要在面板中添加乘法按钮。
    • 然后不仅将 JButton 放置在北部位置,而且将另一个容器放置在北部位置,其中包含更多 JButton。听起来您希望 JPanel 中有多个 JButton,其 GridLayout 为 x 行数(其中 x 是您拥有的按钮数)和 1 列。然后,将带有 GridLayout 的 JPanel 放置在答案中讨论的原始 JPanel 的 North 位置。 GridLayout(不是 GridBagLayout),希望它的组件尽可能多地填充空间,并给每个组件相等的空间,所以它应该让其中的按钮一直向左和向右伸展
    猜你喜欢
    • 2019-09-16
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多