Search code examples
javaswinglayout-managergridbaglayout

GridbagLayout seems to be ignoring component sizes


I am using GridBagLayout for the first time. I have a JFrame which has 2 panel's inside.

  • The frame is of width 1200 and height 800.
  • The left most JPanel has the width of 800 and height of 800.
  • The right most panel has the width of 400 and height of 800.

When they are rendering using GridBagLayout they are both being shown with equal size.

This is the code:

public class DisplayFrame extends JFrame {
    public DisplayFrame() {

            //simple inheritance. 
            super(title);
            setSize(new Dimension(1200, 800));
            setResizable(false);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);

            addComponents();

        } 

        public void addComponents(){

            this.setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();

            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weightx = 1;
            gbc.weighty = 1;
            gbc.fill = GridBagConstraints.BOTH;
            add(new DisplayCanvas(), gbc);

            gbc.gridx++;
            add(new ControlContainer(), gbc);

        }
    }

public class DisplayCanvas extends JPanel{

    public DisplayCanvas() {

        setPreferredSize(new Dimension(800,800));
        this.setBackground(Color.WHITE);
        this.setVisible(true);

    }

     @Override
     public Dimension getPreferredSize() {
         return new Dimension(800, 800);
     }

}
public class ControlContainer extends JPanel{

    public ControlContainer() {
        setPreferredSize(new Dimension(200,200));
        setBackground(Color.GRAY);
        setVisible(true);

    }

 @Override
     public Dimension getPreferredSize() {
         return new Dimension(400, 800);
     }
}

No doubt I am missing something very obvious.


Solution

  • gbc.weightx = 1; and gbc.weighty = 1; are overriding the sizing hints your components are providing. This is basically providing equal weight to both components to fill the remaining space available to the GridBagLayout

    Don't rely on the sizing hints alone, as the window could be resized.

    Also, remember, a frame has decorations, so the frame won't be (and shouldn't be) 1200x800. Allow the content to provide the information about what it needs and use pack to ensure that the viewable area meets your needs and the frame decorations are packed around it. This will make you windows size, ultimately, larger then the content area, but the content area is what matters