为了账号安全,请及时绑定邮箱和手机立即绑定

GridBagLayout 为什么第三列更大?

GridBagLayout 为什么第三列更大?

神不在的星期二 2022-08-03 12:38:39
我试图使按钮的宽度相等,并且它们的总和它们之间的宽度应该与它们上面的JTextField一样宽。法典:window.setLayout(new GridBagLayout());GridBagConstraints gb = new GridBagConstraints();gb.gridx = 0;gb.gridy = 0;gb.gridwidth = 3;gb.fill = GridBagConstraints.HORIZONTAL;gb.gridwidth = GridBagConstraints.REMAINDER;window.add(text,gb); //adds JTextFieldgb.gridwidth = 1;gb.gridy++;window.add(one,gb); //adds JButtongb.gridx++;window.add(two,gb); //adds JButtongb.gridx++;window.add(three,gb); //adds JButton当我使用时,发生这种情况:gb.gridwidth = GridBagConstriants.RELATIVE;
查看完整描述

1 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

您可以通过设置按钮来实现此目的。GridBagConstraints.weightx = 1.0


要注意的另一个关键事项是,我已将文本字段和按钮添加到 a 中,然后将其添加到 的内容窗格中。我没有将文本字段和按钮直接添加到内容窗格中。JPanelJPanelJFrame


import javax.swing.*;

import java.awt.*;


public class EqualWidthButtons

{

  public static void main(String[] args)

  {

    JPanel panel = new JPanel();

    panel.setLayout(new GridBagLayout());


    GridBagConstraints gb = new GridBagConstraints();

    gb.gridx = 0;

    gb.gridy = 0;

    gb.gridwidth = 3;

    gb.fill = GridBagConstraints.HORIZONTAL;

    panel.add(new JTextField(20), gb);


    gb.gridwidth = 1;

    gb.gridy++;

    gb.weightx = 1.0; // This is the important line

    panel.add(new JButton("1"), gb);


    gb.gridx++;

    panel.add(new JButton("2"), gb);


    gb.gridx++;

    panel.add(new JButton("3"), gb);


    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.getContentPane().setLayout(new GridBagLayout());

    frame.getContentPane().add(panel, new GridBagConstraints());

    frame.setBounds(300, 200, 400, 300);

    frame.setVisible(true);

  }

}

输出:

//img1.sycdn.imooc.com//62e9fc07000117cf03770286.jpg

查看完整回答
反对 回复 2022-08-03
  • 1 回答
  • 0 关注
  • 152 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号