我正在编写一个程序,记录用户鼠标移动和点击,并使用 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());
打印 true
整个类代码在这里:
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();
}
}
最佳答案
您必须调用该方法:
Thread t = new Thread();
t.start();
而不是
t.run();
否则不会启动新线程,并且您将在同一线程中执行 run 方法
关于java - 无法从事件调度程序线程调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35073993/