使用 Robot#mousePress 时我的程序停止

When using Robot#mousePress my program halts

当我调用Robot#mousePress我的程序停止时,你可能已经从标题中读到,我的代码如下:

if(read == 2) {
    System.out.println("Click down");
    robot.mousePress(is.read());
}
else if(read == 3) {
    System.out.println("Click up");
    robot.mouseRelease(is.read());
}

其中:

现在,每当我将数据从客户端发送到服务器(PacketID、MouseButton)时,服务器都会正确读取 PacketID 和 MouseButton,并且不会停止(通过打印测试),但是当我尝试添加 Robot#mousePress/Robot#mouseRelease 它停止工作,整个代码都在使用每毫秒运行一次的 ScheduledExecutorService 调度的 Runnable 中。

示例代码:

import java.awt.*;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class Test {

    public static void main(String[] args) throws AWTException {
        Robot robot = new Robot();
        AtomicBoolean bool = new AtomicBoolean();
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            System.out.println("hey");
            if (!bool.get()) {
                bool.set(true);
                robot.mousePress(1);
            }
        }, 0, 1, TimeUnit.MILLISECONDS);
    }

}

编辑:

不是将直接数字传递给 Robot 方法,而是通过 InputEvent.getMaskForButton(number)

传递数字

感谢所有帮助过我的人:D

您向 mousePress 传递了一个非法参数,因此它抛出了一个异常。异常不会从它抛出的线程传播出去,所以只有在 scheduleAtFixedRate returns.[= 的 ScheduledFuture 上调用 get() 时才会看到它。 15=]

例外情况是:

Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.RuntimeException: java.lang.IllegalArgumentException: Invalid combination of button flags
    at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:195)
    at Test.main(Test.java:26)
Caused by: java.lang.RuntimeException: java.lang.IllegalArgumentException: Invalid combination of button flags
    at Test.lambda$main[=10=](Test.java:22)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:654)
    at java.base/java.util.concurrent.FutureTask.runAndReset$$$capture(FutureTask.java:336)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at java.base/java.lang.Thread.run(Thread.java:1521)
Caused by: java.lang.IllegalArgumentException: Invalid combination of button flags
    at java.desktop/java.awt.Robot.checkButtonsArgument(Robot.java:316)
    at java.desktop/java.awt.Robot.mousePress(Robot.java:252)
    at Test.lambda$main[=10=](Test.java:18)