【问题标题】:Detect if any mouse button is being pressed, and if so, which one?检测是否有任何鼠标按钮被按下,如果是,是哪一个?
【发布时间】:2021-03-28 11:16:46
【问题描述】:

基本上,我想查询是否按下了任何鼠标按钮,如果是,是哪一个。 问题是我不使用(持续关注的)UI 环境。它意味着能够在操作系统专注于另一个窗口时在后台运行。我只是设置了一个 Swing GUI 以便于控制。

我该怎么做?

(顺便说一句,我正在尝试在循环中查询它,因此设置事件侦听器效率不高。)

【问题讨论】:

  • 我想解释一下,我试图检测鼠标按钮被按下,以及哪个被按下。修好了
  • 修复了抱歉英语不是我的母语
  • 当操作系统聚焦在另一个窗口上时,它可以在后台运行。 - Swing 不是这样工作的。 Swing 只能在有焦点的 Swing 窗口上生成事件时处理事件。如果你想监听操作系统事件,你需要使用 JNI 或 JNA(我不知道有什么区别)。
  • 我知道,我相信我在问题中也说过。 swing ui 并不是用来处理查询或事件的。
  • 在尝试监控操作系统事件时,Java 不是首选语言。 Java 意味着与操作系统无关。

标签: java swing mouse mouse-buttons


【解决方案1】:

正如其他人所提到的,您需要使用 JNA 才能连接到操作系统的原生 API。幸运的是,有一个很棒的库可以做到这一点jnativehook

这是一些创建Global Mouse Listener的演示代码:

import GlobalScreen;
import NativeHookException;
import NativeMouseEvent;
import NativeMouseInputListener;

public class GlobalMouseListenerExample implements NativeMouseInputListener {
    public void nativeMouseClicked(NativeMouseEvent e) {
        System.out.println("Mouse Clicked: " + e.getClickCount());
    }

    public void nativeMousePressed(NativeMouseEvent e) {
        System.out.println("Mouse Pressed: " + e.getButton());
    }

    public void nativeMouseReleased(NativeMouseEvent e) {
        System.out.println("Mouse Released: " + e.getButton());
    }

    public void nativeMouseMoved(NativeMouseEvent e) {
        System.out.println("Mouse Moved: " + e.getX() + ", " + e.getY());
    }

    public void nativeMouseDragged(NativeMouseEvent e) {
        System.out.println("Mouse Dragged: " + e.getX() + ", " + e.getY());
    }

    public static void main(String[] args) {
        try {
            GlobalScreen.registerNativeHook();
        }
        catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());

            System.exit(1);
        }

        // Construct the example object.
        GlobalMouseListenerExample example = new GlobalMouseListenerExample();

        // Add the appropriate listeners.
        GlobalScreen.addNativeMouseListener(example);
        GlobalScreen.addNativeMouseMotionListener(example);
    }
}

Working with Swing 使用提到的库时,不要忘记阅读线程安全。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2021-03-07
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多