title: GridBagLayout: Swing
body: <p>Mine is a very basic doubt regarding GridBaGLayout in Swing. I am trying to first divide the given frame in three parts with weighty as (0.2, 0.2 and 0.6). The code below, works fine as I see three portions with the respective weights. </p>
  
  <pre><code>        JFrame frame = new JFrame();
          frame.setLayout(new GridBagLayout());
          JPanel p1= new JPanel(), p2 = new JPanel(), p3 = new JPanel();
  
  
      GridBagConstraints c = new GridBagConstraints();
      c.fill = GridBagConstraints.BOTH;
  
      c.weightx = 1;
      c.weighty = 0.2;
      c.gridx = 0;
      c.gridy = 0;
      frame.add(p1,c);
      p1.setBackground(Color.lightGray);
  
      c.gridy = 1;
      frame.add(p2,c);
      p2.setBackground(Color.gray);
  
      c.weighty = 0.6;
      c.gridy = 2;
      frame.add(p3,c);
      p3.setBackground(Color.blue);
  </code></pre>
  
  <p>Next I try to add a JLabel in panel p1. Like this: <code>p1.add(new JLabel("Hi"))</code>. If I observe the opened frame before and after adding, I see the difference in the weights allotted in two cases. First (when JLabel is not added), 0.2,0.2 and 0.6 are allotted. Second, when JLabel is added, first panel increases by a bit and second decreases by a bit. You can see in the below pic also:</p>
  
  <p><a href="https://i.stack.imgur.com/BYutO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BYutO.png" alt="enter image description here"></a></p>
  
  <p>What is the reason for this? As I think it has got something to do with the layout assigning weights as per the available space in the parent frame or panel. But don't quite understand the reasoning properly.<br>
  The weightx/y division is based on the available space. Then how panel p1 and p2 get almost the same height? Let the frame's height be h. When p1 is added, available height is h, then p1 gets 0.2*h which leaves us with available as 0.8h. Now when p2 has to be added, 0.2 of 0.8h will be given to it which is 0.16h. Then how p1 and p2 (in light gray and dark gray background colors) appear to be of the same height?</p>
  
  <p>Also, how can I achieve the constant division and keep the panels of the same weights as they are assigned?</p>