Search code examples
javaswingjscrollpanejcomponent

panel doesn't want to scroll


I have this piece of code (a panel that contains other JComponents, in this case JButtons) and a problem.

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.util.*;

public class JTagPanelTest extends JPanel{

    public JTagPanelTest(){
        setLayout(new FlowLayout(FlowLayout.LEADING, 2, 0));
    }

    public void initializeTags(List<String> tags){
        tags.forEach(tag -> add(new JButton(tag)));
    }

    public static void main(String[] args){
        EventQueue.invokeLater(() -> {
            try{
                String lookAndFeelName = UIManager.getSystemLookAndFeelClassName();
                UIManager.setLookAndFeel(lookAndFeelName);
            }
            catch(Exception e){
                e.printStackTrace();
            }

            JTagPanelTest test = new JTagPanelTest();
            test.initializeTags(Arrays.asList("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
                "012", "qwer", "z<xc", "rty", "poiu", "gfj", "zxcv", "mjnb", "mko", "nij", "bhu"));
            JScrollPane scrollPane = new JScrollPane(test);
            scrollPane.setHorizontalScrollBar(null);
            test.setPreferredSize(new Dimension(200, 100));
//          scrollPane.setPreferredSize(new Dimension(200, 180));
            JFrame frame = new JFrame("Test");
            frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(new Dimension(200, 180));
            frame.setLocationRelativeTo(null);
            frame.setResizable(false);
            frame.setVisible(true);
        });
    }

}

I though it was enough to put my JTagPanelTest inside a JScrollPane to make it scrolling but it's not so, and I really don't know why.

It was of no use calculating the final height of the internal panel, as it results 0.

Note that the number of JButtons are not fixed, so the panel has to be scrollable in order to show all the "buttons".

Is there someone who can make me aware of my mistake?

Thank you


Solution

  • You tried the right approach by setting preferred size on scrollPane.

    So revert to that change. The reason it is not scrolling is because your content is not added to align vertically. Set a layout the helps add items vertically.

    For example:

    test.setLayout(new BoxLayout(test, BoxLayout.Y_AXIS));
    //test.setPreferredSize(new Dimension(200, 100));
    scrollPane.setPreferredSize(new Dimension(200, 180));