Reputation: 325
So I have the following code:
public static void main(String[] args) throws AWTException, InterruptedException {
Robot robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(40);
// This works fine
robot.mouseMove(40, 130);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.delay(200);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(200);
// The 'a' is never inputted
robot.keyPress(KeyEvent.VK_A);
robot.delay(200);
robot.keyRelease(KeyEvent.VK_A);
}
This code successfully moves the mouse to the location 40, 130 and clicks. I make sure to have a text editor open in this location so that it becomes focused.
The next bit of code is the issue. The keyPress/Release snippet works perfectly fine for other codes. (Like 100, corresponding to the number 4.) But for some reason the letter 'a' will not be printed into the text editor.
I have tried having the program continually loop and print a for ~5 seconds. After the programatic click it will not print 'a' in the text editor. If I click on the editor again myself during this time, the string of 'a's will then start to appear.
What is causing this behavior and how can I fix it?
Upvotes: 0
Views: 941
Reputation: 1254
As i assumed in my comments i think you have a problem focusing the editor correctly.
You can try to use the Windows solution by doing ALT
+TAB
and then release it to select the editor.
Robot robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(40);
robot.keyPress(KeyEvent.VK_ALT);//on mac use VK_META
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_ALT);//on mac use VK_META
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_A);
robot.delay(200);
robot.keyRelease(KeyEvent.VK_A);
Upvotes: 1