Mouse Wheel Controller
Posted by Rob Camick on January 10, 2010
The mouse wheel can be used to scroll the viewport in a scroll pane. Have you ever wondered how the scroll amount is determined? Better yet, have you ever wanted to control the scroll amount?
Since I only have access to Windows XP, I can only answer the first question with regards to Windows XP. In this case, the scroll amount can be configured by using the Mouse application from the Control Panel:
- select the “Buttons” tab
- in the “Scroller” area you will find the “Scrolling Size”
On my computer the default is “3 lines”.
What does “lines” mean? After all, you can scroll components like panels, trees, tables, which don’t necessarily have the concept of lines, in addition to text components? Hopefully you read my last entry on the Scrollable Panel where we implemented the Scrollable interface so that you could set the scrollable “block increment” or “unit increment” on a panel. Well, in this case the lines refers to the unit increment, so my default scroll amount is, 3 x the unit increment.
So, if a user doesn’t like the scroll amount, it can be manually changed using the control panel which will affect all applications that scroll. It is more likely that there may be times when you would like to control the scroll amount of an individual scroll pane through the program. The MouseWheelController class allows you to do this. That is, it will allow you to control the scroll amount of a given JScrollPane as a multiple of the unit increment.
To use the MouseWheelController you simply specify a JScrollPane and the unit multiplier:
MouseWheelController mwc = new MouseWheelController(scrollPane, 1);
The above code would change the scroll amount for each mouse wheel rotation to be
equivalant to the unit increment (ie. a single click on the scrollbar button).
The scroll amount can be changed at any time by using the setScrollAmount() method. A value of zero will result in the default scroll amount being used. The MouseWheelController can also be permanently removed by using the uninstall() method.
Well, thats all there is to say about this one. It doesn’t even require an image or a WebStart program as you can test it in any program with a single line of code. Happy scrolling!
The inspiration for this class came from the solution provided by zweibieren in this