Do Robot methods need to be run on the event queue?

前端 未结 3 1623
小蘑菇
小蘑菇 2020-12-06 05:13

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

3条回答
  •  悲&欢浪女
    2020-12-06 05:27

    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");
        }
    }
    

    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.

提交回复
热议问题