使用GridBagLayout时,按钮不会正确调整大小

时间:2015-07-27 09:54:37

标签: java jbutton 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;
}

2 个答案:

答案 0 :(得分:0)

在行和/或列中具有相同大小的按钮(或任何类型的组件)的方法是创建网格。为按钮制作1行网格,对于按住按钮的面板,可能需​​要3行网格。这可能不是您想要的,我无法从您的描述中看出,但网格是用于相同大小的组件的,并且嵌套网格(或任何布局)是良好Swing布局的标准。

答案 1 :(得分:0)

我设法通过在顶部列中添加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));