5

I'm having what I am sure is very much a beginners problem with my JScrollPanes. The problem is that the vertical scrollbar overlaps the components within the enclosed panel (on the right hand side). It becomes a bit of a pain when the scrollbar overlaps the drop-down bit of JComboBoxes.

I have boiled the problem down to this little snippet - I hope it illustrates the issue.

public class ScrollTest extends JFrame
{
    public ScrollTest()
    {
        super("Overlap issues!");
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(100,0));

        for(int b=0;b<100;++b)
        {
            panel.add(new JButton("Small overlap here ->"));
        }

        JScrollPane scrollpane = new JScrollPane(panel);
        add(scrollpane);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) 
    {
        new ScrollTest();
    }
}

I had a look first but couldn't see if anyone else had already addressed this problem. Sorry if it's a duplicate and many thanks for any help anyone can offer a java-newb like me!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
miklatov
  • 63
  • 1
  • 8

1 Answers1

4

The problem is that the default for a JScrollPane is to layout the components with a default of JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED which in turn adds the scrollbar without laying out the components again.

In your example you know you will need a scrollbar so change it to always display the scrollbar

public class ScrollTest extends JFrame
{
    public ScrollTest()
    {
        super("Overlap issues!");
        JPanel panel = new JPanel();
        //Insets insets = panel.getInsets();
        //insets.set(5, 5, 5, 25);
        //insets.set(top, left, bottom, right);
        panel.setLayout(new GridLayout(100,0));

        for(int b=0;b<100;++b)
        {
            panel.add(new JButton("Small overlap here ->"));
        }

        JScrollPane scrollpane = new JScrollPane(panel);
        scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        add(scrollpane);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) 
    {
        new ScrollTest();
    }
}
Romain Hippeau
  • 24,113
  • 5
  • 60
  • 79
  • 1
    +1 A similar usage appears in [`TableAddTest`](http://stackoverflow.com/questions/7519244/jar-bundler-using-osxadapter-causing-application-to-lag-or-terminate/7519403#7519403). – trashgod Sep 23 '11 at 15:01
  • +1, although when the scrollbar is made visible the components are layed out again. The problem is that the layout manager can't resize the frame so the scrollbar is painted over top of the button. – camickr Sep 23 '11 at 15:10