Java ScrollPane overlapping contents
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);
开发者_JS百科 }
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!
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();
}
}
精彩评论