使用 GridBagLayout 时按钮无法正确调整大小

Buttons wont resize correctly when using a GridBagLayout

我正在尝试使用 Java 的 GridBagLayout 创建一个包含 6 个按钮的表单。

布局应该是这样的:http://imgur.com/u9sfKoJ

所以它应该是顶部有两个大按钮,下面有 4 个较小的按钮,但大小相同。 从上图中可以看出,它们的尺寸并不完全相同。 我该如何解决这个问题?

这是我必须列出的代码:

public void InitialiseComponents() {
    btnSouthWestBlockManagement = new JButton();
    btnDevonBlockManagement = new JButton();
    btnAccounts = new JButton();
    btnContacts = new JButton();
    btnIssuesRegister = new JButton();
    btnMaintainance = new JButton();

    btnDevonBlockManagement.setText("Devon Block Management");
    btnSouthWestBlockManagement.setText("South West Block Management");
    btnAccounts.setText("Accounts");
    btnContacts.setText("Contacts");
    btnIssuesRegister.setText("Issues Register");
    btnMaintainance.setText("Maintainance");

    this.add(btnDevonBlockManagement, sizeComponent(0, 0, 2, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0.5, 0.5));
    this.add(btnSouthWestBlockManagement, sizeComponent(2, 0, 2, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0.5, 0.5));
    this.add(btnAccounts, sizeComponent(0, 1, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0.25, 0.5));
    this.add(btnContacts, sizeComponent(1, 1, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0.25, 0.5));
    this.add(btnIssuesRegister, sizeComponent(2, 1, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0.25, 0.5));
    this.add(btnMaintainance, sizeComponent(3, 1, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0.25, 0.5));

}

protected GridBagConstraints sizeComponent(int gridx, int gridy, int gridwidth, int gridheight, int fill, int anchor, double weightx, double weighty) {
    GridBagConstraints gridBagConstraints;
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = gridx;
    gridBagConstraints.gridy = gridy;
    gridBagConstraints.gridwidth = gridwidth;
    gridBagConstraints.gridheight = gridheight;
    gridBagConstraints.fill = fill;
    gridBagConstraints.anchor = anchor;
    gridBagConstraints.weightx = weightx;
    gridBagConstraints.weighty = weighty;
    return gridBagConstraints;
}

让按钮(或任何类型的组件)在行 and/or 列中大小相等的方法是创建一个网格。为按钮制作 1 行网格,也许为包含按钮的面板制作 3 行网格。这可能不是你想要的,我无法从你的描述中看出,但是网格是用于相同大小组件的东西,嵌套网格(或任何布局)是良好 Swing 布局的标准。

我设法通过在顶部列中添加 struts 来使所有组件保持相同大小来解决此问题。我使用的代码是

    this.add(Box.createHorizontalStrut(100), sizeComponent(0, 0, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0, 0));
    this.add(Box.createHorizontalStrut(100), sizeComponent(1, 0, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0, 0));
    this.add(Box.createHorizontalStrut(100), sizeComponent(2, 0, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0, 0));
    this.add(Box.createHorizontalStrut(100), sizeComponent(3, 0, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0, 0));