Search code examples
javaswinguser-interfacelayout-managergridbaglayout

GridBagLayout why is the third column bigger?


I'm trying to make the buttons equaly wide and together they should be as wide as the JTextField above them. code:

window.setLayout(new GridBagLayout());
GridBagConstraints gb = new GridBagConstraints();

gb.gridx = 0;
gb.gridy = 0;
gb.gridwidth = 3;
gb.fill = GridBagConstraints.HORIZONTAL;
gb.gridwidth = GridBagConstraints.REMAINDER;
window.add(text,gb); //adds JTextField

gb.gridwidth = 1;
gb.gridy++;
window.add(one,gb); //adds JButton
gb.gridx++;
window.add(two,gb); //adds JButton
gb.gridx++;
window.add(three,gb); //adds JButton

Screenshot

When I use gb.gridwidth = GridBagConstriants.RELATIVE; this happens:

Screenshot

Thanks in advance.


Solution

  • You can achieved this by setting GridBagConstraints.weightx = 1.0 for buttons.

    Another key thing to notice is that I have added text field and buttons to a JPanel and then added that JPanel to the content pane of JFrame. I have not added text field and buttons directly to the content pane.

    import javax.swing.*;
    import java.awt.*;
    
    public class EqualWidthButtons
    {
      public static void main(String[] args)
      {
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
    
        GridBagConstraints gb = new GridBagConstraints();
        gb.gridx = 0;
        gb.gridy = 0;
        gb.gridwidth = 3;
        gb.fill = GridBagConstraints.HORIZONTAL;
        panel.add(new JTextField(20), gb);
    
        gb.gridwidth = 1;
        gb.gridy++;
        gb.weightx = 1.0; // This is the important line
        panel.add(new JButton("1"), gb);
    
        gb.gridx++;
        panel.add(new JButton("2"), gb);
    
        gb.gridx++;
        panel.add(new JButton("3"), gb);
    
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridBagLayout());
        frame.getContentPane().add(panel, new GridBagConstraints());
        frame.setBounds(300, 200, 400, 300);
        frame.setVisible(true);
      }
    }
    

    Output:

    enter image description here