【问题标题】:How does gridwidth and gridheight work (Java guid GridBagLayout)?gridwidth 和 gridheight 如何工作(Java guid GridBagLayout)?
【发布时间】:2014-10-10 01:52:45
【问题描述】:

我制作了 5 个简单的按钮来查看 GridBagLayout 约束是如何工作的,并将它们设置成十字形。我尝试尝试北方的网格宽度,gbc.gridwidth = 2; (因为默认是 0,然后是 1 和 2,它们是 3 列)准确地说。它不应该在 North 按钮所在位置的 x 轴上占据 3 列吗?但是当你运行它时,按钮都会重叠。请帮忙解释一下是什么问题?谢谢

    JPanel jp = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    JButton jb1 = new JButton("North");
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 2; //Here, it won't take up three columns just at the top where it sits
    jp.add(jb1, gbc);

    JButton jb2 = new JButton("West");
    gbc.gridx = 0;
    gbc.gridy = 1;
    jp.add(jb2, gbc);

    JButton jb3 = new JButton("Center ");
    gbc.gridx = 1;
    gbc.gridy = 1;
    jp.add(jb3, gbc);

    JButton jb4 = new JButton("East");
    gbc.gridx = 2;
    gbc.gridy = 1;
    jp.add(jb4, gbc);

    JButton jb5 = new JButton("South");
    gbc.gridx = 1;
    gbc.gridy = 2;
    jp.add(jb5, gbc);

    add(jp);

    setVisible(true);

【问题讨论】:

    标签: java swing layout-manager gridbaglayout


    【解决方案1】:

    核心问题是,你没有重置约束……

    JButton jb1 = new JButton("North");
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 2; //Here, it won't take up three columns just at the top where it sits
    jp.add(jb1, gbc);
    
    JButton jb2 = new JButton("West");
    // Still using the gridwidth value from before...
    gbc.gridx = 0;
    gbc.gridy = 1;
    jp.add(jb2, gbc);
    

    这意味着对于所有其他控件,gridwidth 的值仍设置为 2...

    在添加jb1 后尝试添加gbc = new GridBagConstraints();

    另外,由于某种原因,gridwidth 不是零索引,它从 1 开始,所以您可能想改用 3...

    JButton jb1 = new JButton("North");
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 3; //Here, it won't take up three columns just at the top where it sits
    jp.add(jb1, gbc);
    
    gbc = new GridBagConstraints();
    JButton jb2 = new JButton("West");
    gbc.gridx = 0;
    gbc.gridy = 1;
    jp.add(jb2, gbc);
    

    现在,我可能是错的,但您似乎试图让北按钮控制整个上排,类似于...

    为此,您需要...

    JButton jb1 = new JButton("North");
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 3; //Here, it won't take up three columns just at the top where it sits
    gbc.fill = GridBagConstraints.HORIZONTAL;
    jp.add(jb1, gbc);
    

    还有……

    【讨论】:

    • 单独使用 gridwidth 会做什么?在这种情况下,我认为它会做和 GridBagConstraints.HORIZONTAL 一样的事情;通过在第一行占据 3 列。另外,在每个单独的按钮约束之后,我是否必须每次都重置?
    • gridwidth 就像 html 的span 中的table,它描述了组件可以跨越/占用的列数
    猜你喜欢
    • 2015-11-14
    • 2019-06-05
    • 1970-01-01
    • 2014-08-21
    • 2013-07-12
    • 2021-11-28
    • 1970-01-01
    • 2014-11-23
    • 2012-10-10
    相关资源
    最近更新 更多