SWT Scale and Scroll Mouse

If you use a SWT Scale object (a.k.a. a Slider), you might want to have it move as your user uses their scroll wheel on their mouse. Here’s the code to make it happen.

Scale verticalScale = new Scale(composite, SWT.VERTICAL);
verticalScale.addMouseWheelListener(new MouseWheelListener() {
    public void mouseScrolled(final MouseEvent e) {
        Scale src = (Scale)e.getSource();
        src.setSelection( src.getSelection() - e.count );
    }
});

You can scroll faster by doing (2*e.count) or similar… Note that it is necessary to subtract the MouseEvent.count because in a vertical orientation, a Scale’s max value is at the bottom, not at the top.

You can also do this generically for horizontal and vertical scales with the following MouseWheelListener:

MouseWheelListener wheelListener = new MouseWheelListener() {
	public void mouseScrolled(final MouseEvent e) {
		Scale src = (Scale)e.getSource();
		if( (src.getStyle() & SWT.VERTICAL) != 0 ) {
			src.setSelection( src.getSelection() - e.count );
		} else {
			src.setSelection( src.getSelection() + e.count );
		}
	}
};

If you don’t want to respond to the scroll wheel for horizontal scales, you can simply comment out the else block.