Search code examples
javaswingjscrollpaneboxlayout

Stop expansion of JScrollPane within a BoxLayout


The JScrollPane in the JPanel below expands to fill the Frame. How can I stop this expansion so that the size of the JScrollPane is the size of the JButton within it?

  public class GUITest extends JFrame {

    public GUITest() {
        setPreferredSize(new Dimension(700, 500));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        add(mainPanel);

        JButton button1 = new JButton();
        JButton button2 = new JButton();
        JButton button3 = new JButton();

        JScrollPane pane1 = new JScrollPane();
        mainPanel.add(button1);
        mainPanel.add(pane1);
        pane1.setViewportView(button2);
        mainPanel.add(button3);

        //Display the window.
        super.pack();
        super.setLocationRelativeTo(null);
        super.setVisible(true);
    }
}

I tried

pane1.setMaximumSize(button2.getPreferredSize());

but the scrollbars appear and I can't see the button. Also, in my real program, the components within the JScrollPane will be dynamically added during runtime so I will need the JScrollPane to expand for this.


Solution

  • Use

    pane1.setPreferredSize(button2.getPreferredSize());
    

    If you still have autoresizing problems fix the panel size with:

    pane1.setMaximumSize(button2.getPreferredSize());
    pane1.setMinimumSize(button2.getPreferredSize());