Search code examples
javaswinglayout-managergridbaglayout

GridBagLayout and JButtons


I haven't found an answer or maybe I don't understand and answer. What I'm trying to do is display 2 buttons ion one row spaced separated by one or two spaces. When I do this with labels and text fields it works perfectly but with buttons no such luck,

gridBagConstraints.weighty = 0.1;
gridBagConstraints.weightx = 1;

gridBagConstraints.gridy = 0;
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = GridBagConstraints.NONE;
gridBagConstraints.anchor = GridBagConstraints.LINE_END;
gridBagConstraints.insets = new Insets(0, 0, 0, 5);
add(streetLabel, gridBagConstraints);

gridBagConstraints.gridy = 0;
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = GridBagConstraints.LINE_START;
gridBagConstraints.insets = new Insets(0, 0, 0, 0);
add(streetField, gridBagConstraints);

Works great!

gridBagConstraints.weighty = 2.0;
gridBagConstraints.weightx = 1;

gridBagConstraints.gridy = 4;
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = GridBagConstraints.FIRST_LINE_START;

gridBagConstraints.insets = new Insets(0 , 0, 0, 5);
add(addBtn, gridBagConstraints, 0);

gridBagConstraints.weighty = 2.0;
gridBagConstraints.weightx = 0.1;

gridBagConstraints.gridy = 4;
gridBagConstraints.gridx = 1;
gridBagConstraints.gridwidth = 0;
gridBagConstraints.insets = new Insets(0, 0, 0, 0);
gridBagConstraints.anchor = GridBagConstraints.FIRST_LINE_END;
add(cancelBtn, gridBagConstraints);

Not so Great.

enter image description here


Solution

  • I recommend that you remove all uses of weightx and weighty. They are not doing what you think.

    The weights only apply when there is extra space in your grid. They are not applicable to your form.

    Also, gridBagConstraints.gridwidth = 0; does not make sense; if something is in the grid, it can’t span zero cells. gridwidth and gridheight must be positive (or a special value like REMAINDER or RELATIVE).

    A good way to accomplish your goal is by nesting a JPanel with a different layout, which contains only your buttons, inside your GridBagLayout:

    JPanel buttonPanel = new JPanel();
    buttonPanel.add(addBtn);
    buttonPanel.add(cancelBtn);
    
    gridBagConstraints.gridy = 4;
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gridBagConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
    
    gridBagConstraints.insets = new Insets(0, 0, 0, 5);
    add(buttonPanel, gridBagConstraints);
    

    Notice the use of GridBagConstraints.REMAINDER to make the panel span all cells horizontally.