Question

I have developed a desktop application. Now in that app I want to add panel with a scrollbar. I am trying using JScrollPane, but its not working.

JPanel paraJPanel = new JPanel();
JScrollPane SP_para_list = new JScrollPane(paraJPanel);
add(SP_para_list).setBounds(10,30,250,350); 

This way I am adding scrollbars to panel. But it shows only empty panel with borders. It is not showing components in the panel. Although I have added several labels in it. Is it correct? Is there any other way to add scroll bar to panel.

Thanks in advance

Was it helpful?

Solution

You need to set the PreferredSize for the panel, to make the scrollbar show up, like below.

even you do not set a layout, the panel already has a default layout set.

public static void main(String[] args)
{
    JFrame frame = new JFrame();
    JPanel panel = new JPanel()
    {
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(800, 1000);
        }
    };
    panel.add(new JLabel("Test1"));
    panel.add(new JLabel("Test2"));
    frame.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);
    frame.setSize(600, 800);
    frame.setVisible(true);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top