Search code examples
javaswingawtlayout-managergridbaglayout

GridBagLayout - Unintended added/and changed spacing


So, I have a problem with the changed spacing between panels (containing JTextAreas) when I add panels, see this picture. :D

Example

When a button is pressed the first time addTextArea() is called. State 1 -> state 2 in the picture. And the problem is that the panel_buttons isn't as close to the newly added WorkDescription (JTextArea). And when the button is pressed multiple times, the spacing between them change.

The buttons did a big jump before, but with; c.weighty = 0.1 - 0.3 the jump is smaller.

// The panel is placed in the center of a JFrame (BorderLayout)
public CONSTRUCTOR {

    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    // ...
    c.anchor = GridBagConstraints.NORTHWEST;
    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = 1;
    c.gridheight = 1;
    // this is how everything looks at (first pic) start.
    panel.add(panel_buttons, c);   // panel_buttons is at the right place
}

The method that adds a new WorkDescription, namely a JTextArea:

public void addTextArea() {

    WorkDescription wd = new WorkDescription(); //WorkDescription extends JPanel

    panel.remove(panel_buttons); 
    c.weighty = 0.25;       // I've messed around with the weighty alot.
                            // 0.2-0.25 makes the panel_buttons do the least amout of 'down-jump'
    panel.add(wd, c);

    if(c.gridy < 3 ) {
        c.gridy ++;
        c.weighty = 1;

        panel.add(panel_buttons, c);
    }
    panel.revalidate();
    panel.repaint();
}

Solution

  • The best solution I found was to,

    Switch from GridBagLayout to GridLayout.

    private JPanel panel_Center = new JPanel(new GridLayout(5,1)); 
    

    And then, of course, remove all GridBagConstraints

    public void addTextArea() {
    
        WorkDescription wd = new WorkDescription();
    
        panel.remove(panel_buttons); 
        panel.add(wd);
    
        if(addedWorks < 4 ) {       
    
            addedWorks++;
            panel.add(panel_buttons);
    
        }
    
        panel.revalidate();
        panel.repaint();
    }