GridbagLayout seems to be ignoring component sizes

旧城冷巷雨未停 提交于 2020-01-06 01:44:14

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/28619238/gridbaglayout-seems-to-be-ignoring-component-sizes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!