是否需要在事件队列上运行Robot方法? [英] Do Robot methods need to be run on the event queue?

查看:170
本文介绍了是否需要在事件队列上运行Robot方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Robot是AWT库的一部分,但它似乎与大多数库的其他部分完全不同。我正在创建一个Swing GUI,它将Swing与Java Native Access(JNA)和Robot混合在一起,以允许Java驱动某些MS Windows / Citrix工作程序。我的直觉是,因为Robot会在平台的本机输入队列上排队事件,我想要做的最后一件事是在EDT上运行它,但另一方面,AWT和Swing库中的大多数类应该在 on Swing事件线程上运行。因此,为了让我在脑海中澄清这一点,请让我尽可能具体地问一个问题:

Robot is part of the AWT library, but it seems quite different from most all the rest of the library. I am creating a Swing GUI that mixes Swing with Java Native Access (JNA) and Robot to allow Java to drive some MS Windows/Citrix work programs. My gut feeling is that since Robot will queue events on the "platform's native input queue" that the last thing I want to do is to run it on the EDT, but on the other hand, most of the classes in the AWT and Swing libraries should be run on the Swing event thread. So to try clarify this in my mind for me let me ask as specific a question as possible:

应该是机器人方法(特别是按键和释放,鼠标移动,鼠标按下和释放)在Swing事件发送线程(EDT)上运行或不运行?

Should Robot methods (in particular key presses and releases, mouse moves, mouse presses and releases) be run on or off of the Swing event dispatch thread (the EDT)?

推荐答案

机器人您提到的方法在EDT上运行。看一下源代码,发现这些事件方法中的每一个都有一个共同点( afterEvent 调用):

The Robot methods you mentioned should not be run on the EDT. Taking a look at the source code revealed that each one of these "event" methods has one thing in common (the afterEvent call):

public synchronized void keyPress(int keycode) {
    checkKeycodeArgument(keycode);
    peer.keyPress(keycode);
    afterEvent();
}

public synchronized void mousePress(int buttons) {
    checkButtonsArgument(buttons);
    peer.mousePress(buttons);
    afterEvent();
}

// etc

private void afterEvent() {
    autoWaitForIdle();
    autoDelay();
}

private void autoWaitForIdle() {
    if (isAutoWaitForIdle) {
        waitForIdle();
    }
}

public synchronized void waitForIdle() {
    checkNotDispatchThread();
    /* snip */
}

private void checkNotDispatchThread() {
    if (EventQueue.isDispatchThread()) {
        throw new IllegalThreadStateException("Cannot call method from the event dispatcher thread");
    }
}

如果你在EDT上调用任何这些方法的话 Robot.isAutoWaitForIdle true ,将抛出异常。这是有道理的,即使 isAutoWaitForIdle false ,也不应该从EDT调用这些方法。

If you call any of these methods on the EDT while Robot.isAutoWaitForIdle is true, an exception will be thrown. This stands to reason that even if isAutoWaitForIdle is false, these methods shouldn't be called from the EDT.

这篇关于是否需要在事件队列上运行Robot方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆