Java Swing How to - Resize GridBagLayout within JScrollPane








Question

We would like to know how to resize GridBagLayout within JScrollPane.

Answer

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
//  w  w w  . ja  v a 2 s  . co m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class Main {
  public static void main(String[] args) {
    JPanel panel = new JPanel(new GridBagLayout());
    for (int i = 0; i < 25; i++) {
      JTextField field = new JTextField("Field " + i, 20);
      GridBagConstraints constraints = new GridBagConstraints();
      constraints.gridy = i;
      panel.add(field, constraints);
    }
    JScrollPane scrollPane = new JScrollPane(panel);
    JButton removeButton = new JButton("Remove Field");
    removeButton.addActionListener(e->{
        if (panel.getComponentCount() >= 1) {
          panel.remove(panel.getComponentCount() - 1);
          scrollPane.revalidate();
          scrollPane.repaint();
        }
    });
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(640, 480);
    f.setLocation(200, 200);
    f.getContentPane().add(scrollPane);
    f.getContentPane().add(removeButton, BorderLayout.SOUTH);
    f.setVisible(true);
  }
}