Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing: JScrollPane not working

I have a JPanel which contains some fields. The height of the JPanel is limited so I have to put a JScrollPane around it so people can scroll down.

As you can see below, it displays perfectly. But you can't scroll down (or up).

DetailPanel detail = new DetailPanel();
JScrollPane jsp = new JScrollPane(detail);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setBounds(745, 10, 235, 225);
add(jsp);

Detail panel:

private void init(){
            setLayout(null);
            setSize(140, 400);
            int x = 5, y = 0;
            for(int i = 0; i < lbls.length; i++) {
                JLabel lbl = new JLabel(lbls[i]);
                lbl.setBounds(x, y, 200, 25);
                add(lbl);
                fields[i] = new JTextField();
                fields[i].setBounds(x, y+26, 200, 25);
                add(fields[i]);
                y+=50;
            }
        }

enter image description here

like image 465
Reinard Avatar asked Jan 18 '23 00:01

Reinard


1 Answers

Your DetailPanel has no layout manager associated with it, which means it doesn't expand when you add children to it, which means the JScrollPane doesn't have anywhere to scroll. Either call setLayout() on your DetailPanel or override getPreferredSize() to add up the heights of its children and return a meaningful value.

like image 143
Dan O Avatar answered Jan 29 '23 02:01

Dan O