Javafx和Sun.glass机器人由于使用Threads而导致问题IllegalStateException

时间:2014-06-28 22:32:31

标签: java multithreading javafx

我正在编写一个JavaFX控制器,每5秒移动一次鼠标。执行此操作时,此控制器还会同时执行其他一些操作。因此,我为每个任务使用了单独的线程。以下是我的代码:

Thread dynamicMouseThread = new Thread(new Runnable() {
    @Override
    public void run() {
        boolean isRunning = true;
        long timeout = 5000;
        int x = 5;
        Robot robot = com.sun.glass.ui.Application.GetApplication().createRobot();
        while (isRunning) {
            try {
                Thread.sleep(timeout);
            } catch (InterruptedException ex) {
                isRunning = false;
            }
            x = x == 5 ? x + 5 : 5;
            robot.mouseMove(x, 5);  // This line causes the error.
        }
    }
});


@Override
public void initialize(URL url, ResourceBundle rb) {
    dynamicTimerThread.setName("Dynamic Timer Thread");
    dynamicMouseThread.setName("Dynamic Mouse Thread");
    dynamicTimerThread.start();
    dynamicMouseThread.start();
}

这是我似乎得到的错误。请帮帮我。我做错了什么?

Exception in thread "Dynamic Mouse Thread" java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = Dynamic Mouse Thread
at com.sun.glass.ui.Application.checkEventThread(Application.java:427)
at com.sun.glass.ui.Robot.<init>(Robot.java:52)
at com.sun.glass.ui.win.WinRobot.<init>(WinRobot.java:33)
at com.sun.glass.ui.win.WinApplication.createRobot(WinApplication.java:205)
at main.SubDocumentController$1.run(SubDocumentController.java:56)
at java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:2)

你得到的错误有点误导,它应该真正引用JavaFX Application Thread,这是必须发生对JavaFX对象的所有访问的地方。

在JavaFX中,你不应该像这样创建线程。 javafx.concurrent包中有一些并发类,例如TaskWorker,它们基本上为您包裹Runnable。使用Platform#runLater(Runnable)在正确的上下文中执行这些操作。

所以,你的代码应该是这样的:

Platform.runLater(new Runnable() {
    @Override
    public void run() {
        // ...
        Robot robot = com.sun.glass.ui.Application.GetApplication().createRobot();
        // ...
        robot.mouseMove(x, 5);
    }
});