【问题标题】:Javafx and Sun.glass robot causing problems IllegalStateException due to use of ThreadsJavafx 和 Sun.glass 机器人由于使用线程而导致问题 IllegalStateException
【发布时间】:2014-06-28 22:32:30
【问题描述】:

我正在编写一个 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)

【问题讨论】:

    标签: java multithreading javafx


    【解决方案1】:

    你得到的错误有点误导,它应该真的是指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);
        }
    });
    

    【讨论】:

    • 我确实尝试过使用 Platform.runLater 但它导致了同样的异常。另外,当我使用 Task 作为包装器时,我没有异常,但是鼠标不会移动,这很奇怪,因为我知道发生了一些异常。
    • 奇数。您遇到的错误应该用runLater 修复。快速搜索发现this blog post,它也使用与我建议的完全相同的机制,用于 Glass 机器人......
    • 实际上我的任务实现有点错误。但是,您的评论帮助我重新评估了这一点。现在可以了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    相关资源
    最近更新 更多