Search code examples
javauser-interfacegridbaglayout

GridBagLayout Grid Width


When I use the code below to make a JFrame using a GridBagLayout, this is the output: Output

I want the first three rows' buttons to all have equal widths, but they aren't. I also want the fourth row buttons to all have equal widths. How can I do this?
Here is the code:

public Test() {
    setTitle("Calculator");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JMenuBar menu = new JMenuBar();
    setJMenuBar(menu);

    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    field = new JTextField(20);
    field.setFont(new Font("Cambria Math", Font.PLAIN, 32));
    field.setEditable(false);
    updateDisplay();
    c.fill = GridBagConstraints.HORIZONTAL;
    //c.insets = new Insets(9,9,9,9);
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 24;
    c.gridheight = 2;
    add(field, c);


    // sin, cos, tan
    c.weightx = 0;
    c.gridwidth = 4;
    c.gridheight = 1;
    c.gridx = 0;
    c.weightx = 0;
    c.gridy = 2;
    add(createButton("sin"), c);
    c.gridx = 4;
    add(createButton("cos"), c);
    c.gridx = 8;
    add(createButton("tan"), c);
    // cot, sec, csc
    c.gridx = 0;
    c.gridy = 3;
    add(createButton("cot"), c);
    c.gridx = 4;
    add(createButton("sec"), c);
    c.gridx = 8;
    add(createButton("csc"), c);

    // asin, acos, atan
    c.gridx = 0;
    c.gridy = 4;
    add(createButton("asin"), c);
    c.gridx = 4;
    add(createButton("acos"), c);
    c.gridx = 8;
    add(createButton("atan"), c);

    // atan2, acot, asec, acsc
    c.gridy = 5;
    c.gridwidth = 3;
    c.weightx = 0;
    c.gridx = 0;
    add(createButton("atan2"), c);
    c.gridx = 3;
    add(createButton("acot"), c);
    c.gridx = 6;
    add(createButton("asec"), c);
    c.gridx = 9;
    add(createButton("acsc"), c);

    pack();
    setVisible(true);
}
public JButton createButton(String name) {
    JButton button = new JButton(name);
    button.setActionCommand(name);
    button.addActionListener(this);
    button.setFont(new Font("Dialog", Font.PLAIN, 25));
    return button;
}

Solution

  • I don't think you can use GridBagLayout for this.

    Instead create a main panel with a GridLayout(0, 1);

    Then create second panel for the first 3 buttons with a GridLayout(1, 0) and add this panel to the first panel.

    Repeat for the other three rows.