Java.awt.Robot keyPress and keyRelease not working

2019-06-14 10:31发布

问题:

Whenever I try using the java.awt.Robot keyPress or keyRelease, it gives me the error message pid(25807)/euid(501) is calling TIS/TSM in non-main thread environment, ERROR : This is NOT allowed. Please call TIS/TSM in main thread!!!. No matter how simple I make the code, it keeps giving this error message. This is my code:

package com;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

public class JavaRobotExample {
    public static void main(String[] args) throws AWTException {
        Robot robot = new Robot();

        robot.keyPress(KeyEvent.VK_A);
        robot.keyRelease(KeyEvent.VK_A);
    }
}

This is the textbook example I found, yet it still gives that error message. I've been searching for so long trying to figure out what is wrong. I use MacOS Mojave 10.14.2 on a MacBook Pro, and I have given Eclipse (what I use to compile the code) privacy access. Here is a screenshot of everything I use for this: My code

Does anyone else have this issue? I should also note that the error message is sent multiple times, even though it only presses the key once.

回答1:

Follow the steps below,

  1. Settings -> Security & Privacy
  2. Scroll down to "Accessibility"
  3. Click the lock button at the bottom and unlock the security and privacy preferences
  4. Click on '+' icon and your program (Eclipse IDE in my case) and try running again

The Eclipse IDE still shows "This is NOT allowed. Please call TIS/TSM in main thread!!!" but both Keyboard and Mouse events work.



回答2:

This message is generated by Main Thread Checker in MacOS. Activities like Robot key press in background should be excluded from this check. You can disable this check and verify whether it works or not.

Read more about it in following question,

  • What is Main Thread Checker in Xcode 9


标签: java awt robot