繁体   English   中英

当我在Java中使用GridBagLayout时,按钮无法填充所有可用空间

[英]Buttons doesn't fill all available space when I use GridBagLayout in Java

我想创建一个应用程序,其中的按钮排列成不可见的表格。 即使我要调整框架的大小,按钮也应填充假想单元内部的所有可用空间。 我正在使用Swing, GridBagLayout 我已经阅读了一些文章,解决方案是添加.weightx=1.weighty=1 Weightx工作完美,填补了空白,但Weightx却没有。 按钮不会延伸到单元格的高度。 我的代码是否有问题或有什么要解决的问题? 还是我绝对应该使用其他布局?

public class NewClass {
  public void NewClass(){
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    frame.add(panel);
    GridBagLayout layout = new GridBagLayout();
    panel.setLayout(layout);
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;

    gbc.gridx = 0;
    gbc.gridy = 0;
    JButton B11 = new JButton("11");
    panel.add(B11,gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    JButton B12 = new JButton("12");
    panel.add(B12,gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    JButton B21 = new JButton("21");
    panel.add(B21,gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    JButton B22 = new JButton("22");
    panel.add(B22,gbc);

    frame.pack();
    frame.setSize(800,400);
    frame.setVisible(true);
}}

您使用了错误的GridBagConstraints#fill字段值,因为您使用的值告诉布局管理器仅水平填充按钮。

你需要改变

  gbc.fill = GridBagConstraints.HORIZONTAL;

  // gbc.fill = GridBagConstraints.HORIZONTAL;
  gbc.fill = GridBagConstraints.BOTH;

如果您希望按钮同时填充水平和垂直两个方向。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM