20

I am adding a JPanel in a JScrollPane in my project.

All is working fine, but there is one problem about mouse scroll using the mouse-Wheel in JPanel. It's speed is very slow on scrolling. How to make it faster?

My code is :

JPanel panel = new JPanel();

panel.setLayout(new BorderLayout());
objCheckBoxList = new CheckBoxList();
BaseTreeExplorer node = (BaseTreeExplorer)projectMain.objCommon.tree.getLastSelectedPathComponent();
if (node.getObject() != null) {
    cmbList.setSelectedItem(node.getParent().toString());
} else {
    if (node.toString().equalsIgnoreCase("List of attributes")) {
        cmbList.setSelectedIndex(0);
    } else {
        cmbList.setSelectedItem(node.toString());
    }
}

panel.add(objCheckBoxList);

JScrollPane myScrollPanel = new JScrollPane(panel);

myScrollPanel.setPreferredSize(new Dimension(200, 200));
myScrollPanel.setBorder(BorderFactory.createTitledBorder("Attribute List"));
hamena314
  • 2,969
  • 5
  • 30
  • 57
Ronak Jain
  • 2,402
  • 2
  • 24
  • 38

2 Answers2

44

You can set your scrolling speed with this line of code

myJScrollPane.getVerticalScrollBar().setUnitIncrement(16);
Here is details.
Community
  • 1
  • 1
mbaydar
  • 1,144
  • 1
  • 13
  • 18
1

This bug seems to occur because swing interprets the scroll speed in pixels instead of lines of text. If you are looking for a more accessible alternative to the accepted solution, you can use the following function to calculate and set the actual desired scroll speed in pixels:

public static void fixScrolling(JScrollPane scrollpane) {
    JLabel systemLabel = new JLabel();
    FontMetrics metrics = systemLabel.getFontMetrics(systemLabel.getFont());
    int lineHeight = metrics.getHeight();
    int charWidth = metrics.getMaxAdvance();
            
    JScrollBar systemVBar = new JScrollBar(JScrollBar.VERTICAL);
    JScrollBar systemHBar = new JScrollBar(JScrollBar.HORIZONTAL);
    int verticalIncrement = systemVBar.getUnitIncrement();
    int horizontalIncrement = systemHBar.getUnitIncrement();
            
    scrollpane.getVerticalScrollBar().setUnitIncrement(lineHeight * verticalIncrement);
    scrollpane.getHorizontalScrollBar().setUnitIncrement(charWidth * horizontalIncrement);
}

Note that swing does calculate the scroll speed correctly when it contains a single component like a JTable or JTextArea. This fix is specifically for when your scroll pane contains a JPanel.

otoomey
  • 939
  • 1
  • 14
  • 31