Java Swing: JScrollPane not working

Go To


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.setBounds(745, 10, 235, 225);

Detail panel:

private void init(){
            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);
                fields[i] = new JTextField();
                fields[i].setBounds(x, y+26, 200, 25);

enter image description here

2012-04-04 18:09
by Reinard


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.

2012-04-04 18:16
by Dan O
Future reference, as I couldn't get this thing right: trying to use the setter, i.e. setPreferredSize(), is WRONG, as orzechowskid says you need to override the getter, i.e. getPreferredSize(), this is very important - mastazi 2013-09-08 10:32


I could be wrong, but I think this might be happening because DetailPanel's layout is null. What happens if you use a BoxLayout in vertical orientation and call detail.setPreferredSize(new Dimension(140,400));?

2012-04-04 18:17
by CodeBlind
+1 for spotting the culprit -1 for setPrefSize (it's a no-no-never, - kleopatra 2012-04-05 10:12