title: Can components of a gridbaglayout fill parent frame upon resize?
body: <p>I've got a <code>JFrame</code> whose root <code>JPanel</code> is instantiated with a <code>GridBagLayout</code>. At runtime, the panel is populated with components based on some description, and the width, height and x,y coords are given in the description to be used with the <code>gridwidth</code>, <code>gridheight</code>, <code>gridx</code> and <code>gridy</code> fields in <code>GridBagConstraints</code>. The components themselves can be also be <code>JPanel</code>s with their own child components and <code>GridBagConstraints</code>, the GUI is described in a tree so Frame is populated recursively.</p>
  
  <p>The problem I'm having is that when the frame is resized, the inner components are not stretched to fill their given widths and heights. I've given an example of the layout code below, with screenshots.</p>
  
  <pre><code>import javax.swing.*;
  import javax.swing.border.TitledBorder;
  import java.awt.*;
  import java.util.*;
  
  public class GridBagTest extends JPanel {
  
      private final GridBagConstraints gbc = new GridBagConstraints();
  
      public GridBagTest(){
  
          setLayout(new GridBagLayout());
          add(gbcComponent(0,0,1,2), gbc);    
          add(gbcComponent(1,0,2,1), gbc);            
          add(gbcComponent(1,1,1,1), gbc);            
          add(gbcComponent(2,1,1,1), gbc);            
  
      }
  
      //Returns a JPanel with some component inside it, and sets the GBC fields
      private JPanel gbcComponent(int x, int y, int w, int h){
  
          gbc.gridx = x; 
          gbc.gridy = y;
          gbc.gridwidth = w;
          gbc.gridheight = h;
          gbc.fill = GridBagConstraints.BOTH;
          JPanel panel = new JPanel();
          JTextField text = new JTextField("(" + w + ", " + h + ")");
          panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));        
          panel.add(text);
          return panel;
  
      }
  
      public static void main (String args[]){
  
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setContentPane(new GridBagTest());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
      }
  }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/Eu9da.png" alt="When running it">
  <img src="https://i.stack.imgur.com/nkFuR.png" alt="After stretching"></p>
  
  <p>I need it so in picture 2, the inner <code>JPanel</code>s holding the components are resized to fill their respective widths and heights on the <code>GridBagLayout</code>, ideally stretching their components as well. </p>