title: How to vertically fill a JPanel with GridLayout or GridBagLayout?
body: <p>I want to fill a <code>JPanel</code> whose layout is <strong><code>GridLayout</code></strong>, if it's not possible using <code>GridLayout</code> i would like to know if using <code>GridBagLayout</code> is possible and how?</p>
  
  <p>Here's the code:</p>
  
  <pre><code>public class NestedLayoutExample {
  
  public static void main(String[] args) {
  
      Runnable r = new Runnable() {
  
          @Override
          public void run() {
              final JFrame frame = new JFrame("Nested Layout Example");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setMinimumSize(new Dimension(300, 400));
  
              final JPanel gui = new JPanel(new BorderLayout(5,5));
              gui.setBorder( new TitledBorder("BorderLayout(5,5)") );
  
              JPanel dynamicLabels = new JPanel(new BorderLayout(4,4));
              dynamicLabels.setBorder( new TitledBorder("BorderLayout(4,4)") );
              gui.add(dynamicLabels, BorderLayout.CENTER);
  
              final JPanel labels = new JPanel(new GridLayout(4,0,3,3));
              labels.setBorder( new TitledBorder("GridLayout(0,2,3,3)") );
  
              JButton addNew = new JButton("Add Another Label");
              dynamicLabels.add( addNew, BorderLayout.NORTH );
              addNew.addActionListener( new ActionListener(){
                  private int labelCount = 0;
  
                  @Override
                  public void actionPerformed(ActionEvent ae) {
                      labels.add( new JLabel("Label " + ++labelCount) );
                      frame.validate();
                  }
              } );
  
              dynamicLabels.add( new JScrollPane(labels), BorderLayout.CENTER );
  
              frame.setContentPane(gui);
              frame.pack();
              frame.setLocationRelativeTo(null);
              try {
                  // 1.6+
                  frame.setLocationByPlatform(true);
                  frame.setMinimumSize(frame.getSize());
              } catch(Throwable ignoreAndContinue) {}
  
              frame.setVisible(true);
          }
      };
      SwingUtilities.invokeLater(r);
  }}
  </code></pre>
  
  <p>This is what I get the code above:</p>
  
  <p><img src="https://i.stack.imgur.com/srPlQ.png" alt="enter image description here"></p>
  
  <p>And this is what I want:</p>
  
  <p><img src="https://i.stack.imgur.com/7IbIC.png" alt="enter image description here"></p>
  
  <p>Also would like to know about a better way to do it.</p>