2

我正在编写一个记录用户鼠标移动和点击的程序,并使用Robot该类播放它们。

我遇到了这个错误:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalThreadStateException: Cannot call method from the event dispatcher thread

我已经阅读了有关 EDT 的所有内容,人们一直在向您提到必须在另一个线程中运行它才能退出 EDT。

我的问题是:为什么即使我使用了新线程,我的代码也不起作用?

这是代码:

void doAction(Robot robert) {
    int x = ((MouseEvent) event).getXOnScreen();
    int y = ((MouseEvent) event).getYOnScreen();
    Thread safe = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println(SwingUtilities.isEventDispatchThread());
            MouseEvent m = (MouseEvent) this.event; // event is the recording of the click
            robert.mouseMove(x, y); // error traces back to here
            leftClick(robert);
        }
    });
    safe.run();
}

System.out.println(SwingUtilities.isEventDispatchThread());打印为真

整个类代码在这里:

class RoboMouseClick extends RoboAction {

    AWTEvent event;

    public RoboMouseClick(String mouse, int MOUSE_MOVE, AWTEvent event,
            long timeStamp) {
        super(mouse, MOUSE_MOVE, timeStamp);
        this.event = event;
    }

    private void leftClick(Robot robot)
    {
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.delay(200);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        robot.delay(200);
    }

    void doAction(Robot robert) {
        int x = ((MouseEvent) event).getXOnScreen();
        int y = ((MouseEvent) event).getYOnScreen();
        Thread safe = new Thread(() -> {
            System.out.println(SwingUtilities.isEventDispatchThread());
            MouseEvent m = (MouseEvent) event;
            robert.mouseMove(x, y);
            leftClick(robert);
        });
        safe.run();
    }
}
4

1 回答 1

3

您必须调用该方法:

Thread t = new Thread();
t.start();

代替

t.run();

否则不会启动新线程,您将在同一线程中执行 run 方法

于 2016-01-28T23:18:26.553 回答