How do I handle mouse wheel event?

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.MouseWheelEvent;

public class MouseWheelListenerDemo extends JFrame {
    public MouseWheelListenerDemo() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new MouseWheelListenerDemo().setVisible(true));
    }

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("Mouse Wheel Listener Demo");
        setSize(500, 500);

        JTextArea textArea = new JTextArea();
        textArea.addMouseWheelListener(e -> {
            System.out.println("MouseWheelListenerDemo.mouseWheelMoved");

            // If wheel rotation value is a negative it means rotate up, while
            // positive value means rotate down
            if (e.getWheelRotation() < 0) {
                System.out.println("Rotated Up... " + e.getWheelRotation());
            } else {
                System.out.println("Rotated Down... " + e.getWheelRotation());
            }

            // Get scrolled unit amount
            System.out.println("ScrollAmount: " + e.getScrollAmount());

            // WHEEL_UNIT_SCROLL representing scroll by unit such as the
            // arrow keys. WHEEL_BLOCK_SCROLL representing scroll by block
            // such as the page-up or page-down key.
            if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
                System.out.println("MouseWheelEvent.WHEEL_UNIT_SCROLL");
            }

            if (e.getScrollType() == MouseWheelEvent.WHEEL_BLOCK_SCROLL) {
                System.out.println("MouseWheelEvent.WHEEL_BLOCK_SCROLL");
            }
        });

        getContentPane().add(textArea);
    }
}

The scrolling the mouse wheel the code snippet will print something like:

MouseWheelListenerDemo.mouseWheelMoved
Rotated Down... 1
ScrollAmount: 3
MouseWheelEvent.WHEEL_UNIT_SCROLL
MouseWheelListenerDemo.mouseWheelMoved
Rotated Up... -1
ScrollAmount: 3
MouseWheelEvent.WHEEL_UNIT_SCROLL
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.