Java如何处理鼠标滚轮事件?

package org.nhooo.example.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);

        setSize(200, 200);

        JTextArea textArea = new JTextArea();

        textArea.addMouseWheelListener(e -> {

            System.out.println("MouseWheelListenerDemo.mouseWheelMoved");

            // 如果车轮旋转值为负,则表示向上旋转,而

            // 正值表示向下旋转

            if (e.getWheelRotation() < 0) {

                System.out.println("Rotated Up... " + e.getWheelRotation());

            } else {

                System.out.println("Rotated Down... " + e.getWheelRotation());

            }

            // 获取滚动的单位数量

            System.out.println("ScrollAmount: " + e.getScrollAmount());

            // WHEEL_UNIT_SCROLL表示按单位滚动,例如

            //方向键。WHEEL_BLOCK_SCROLL表示按块滚动

            // 例如向上翻页或向下翻页键。

            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);

    }

}

                       

以上是 Java如何处理鼠标滚轮事件? 的全部内容, 来源链接: utcz.com/z/347083.html

回到顶部