Java Native Hook陷入了一个无休止的循环



嘿,所以我正在编写一个自动点击器,当按住鼠标左键时开始点击。我的问题是当我发布它时它不会停止点击!我将不胜感激任何帮助!到目前为止,我的代码如下!

public void nativeMouseClicked(NativeMouseEvent e) {
    System.out.println("Mouse Clicked: " + e.getClickCount());
}
public static boolean released;
public void nativeMouseReleased(NativeMouseEvent e) {
    released=true;
}
public void nativeMousePressed(NativeMouseEvent e) {
    released = false;
        while(released != true) {
            try {
                Mouse.sendLeftClick();
            } catch (AWTException e1) {
                e1.printStackTrace();
            }
            double deviation = 31;
            double mean = 95;
            int min = 65;
            int max = 117;
            Random r = new Random();
            double randGauss = (r.nextGaussian() * deviation);
            long delayPreClamp = Math.round(randGauss + mean);
            long delay = (long) MathUtil.clamp(delayPreClamp, min, max);
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e2) {
                e2.printStackTrace();
                }
            }
}
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());
}
static Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
public static void main(String[] args) {
    try {
        logger.setLevel(Level.OFF);
        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.
    Inter inter = new Inter();
    // Add the appropriate listeners.
    GlobalScreen.addNativeMouseListener(inter);
    GlobalScreen.addNativeMouseMotionListener(inter);
}

提前感谢伙计们!

那是因为您在 nativeMousePressed 中使用 while 循环阻止了事件线程。您需要在不同的线程中执行此处理。

看看ThreadExecutorService等。

最新更新