Java Native Hook陷入无限循环

时间:2017-06-09 11:31:16

标签: java java-native-interface

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

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

先谢谢大家!

1 个答案:

答案 0 :(得分:1)

这是因为您使用nativeMousePressed中的while循环阻止事件线程。您需要在另一个线程中执行此处理。

查看ThreadExecutorService