I'm pretty new to Swing. I have an application that dynamically generates a UI based on an external input. At the top of the panel, there is a JLabel with some heading text, and then a button (which tells the app to reload the dynamically generated stuff), and then below that is a JScrollPane which contains all of the dynamically generated stuff. I want the label and the button to take only as much vertical space as they need, and then the scroll pane to fill all remaining available space.
I'm using GridBagLayout, and setting gbc.fill = BOTH before I add the scroll pane.
I've put together an SSCCE, and when it first loads, the window looks exactly like what I want. But if I resize the window smaller, my expectation is that the scrollpane would continue to consume all available space and that scrollbars would appear. But what happens instead is that as soon as I shrink the window by even a single pixel, the scrollpane becomes tiny, with its contents barely visible.
I found How to get a JScrollPane to resize with its parent JPanel, but that doesn't work when the JScrollPane isn't an only-child, so to speak.
What am I doing wrong?
SSCCE:
public class SwingTest {
public static void main(String[] args) {
JPanel bigPanel = new JPanel();
bigPanel.setLayout(new GridLayout(10, 10));
for (int i = 0; i < 100; i++) {
bigPanel.add(new JCheckBox("Item " + i));
}
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
JFrame mainWindow = new JFrame("Swing Test");
mainWindow.setLayout(new GridBagLayout());
mainWindow.add(new JLabel("Heading"), gbc);
mainWindow.add(new JButton("Button"), gbc);
gbc.fill = GridBagConstraints.BOTH;
mainWindow.add(new JScrollPane(bigPanel), gbc);
mainWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainWindow.setLocationByPlatform(true);
mainWindow.pack();
mainWindow.setVisible(true);
}
}