Search code examples
javaswingmousewheeljslidermouse-listeners

How to move the JSlider with the mouse wheel


I have this code, but nothing happens. I don't know why the degreesSlider.getValue() + 1 does not work. I would be thankful for any suggestions.

degreesSlider.addMouseWheelListener(new MouseWheelListener() {
    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
        int notches = e.getWheelRotation();
        if (notches < 0) {
            System.out.println("Mouse wheel moved UP " + -notches + " notch(es)");
            degreesSlider.setValue(degreesSlider.getValue() + 1);
        } else {
            System.out.println("Mouse wheel moved DOWN " + notches + " notch(es)");
            degreesSlider.setValue(degreesSlider.getValue() - 1);
        }
    }
});

Solution

  • Try running the code from the Swing tutorial on How to Write a Mouse Wheel Listener. When I ran that code is appear that the "notch" only changes for every 3 units of wheel movement. Therefore when you scroll up you actually get 3 down scrolls for every up scroll and the slider slowly moves towards 0.

    As a quick fix I just did:

        if (notches < 0) {
            System.out.println("Mouse wheel moved UP " + -notches + " notch(es)");
            slider.setValue(slider.getValue() + 1);
        } else
        if (notches > 0) {
            System.out.println("Mouse wheel moved DOWN " + notches + " notch(es)");
            slider.setValue(slider.getValue() - 1);
        }