Search code examples
javafocuskeypressawtrobot

Robot.keypress using a Thread: sometimes doesn't focus on the right window


I'm using a Robot instance to programmatically press keys. Those keys are pressed inside a while loop using a class that extends Thread.

My app has only one window, the main window.

Even though I request the focus on the correct window every time I press on the button that start the thread, it happens that sometimes the keypress events are launched elsewhere instead of my app.

Why does that happen?

Here's the snippet:

try {
            Robot robot = new Robot(); 

            while(!stopped)
            {
               fireRandomKey(robot);
               Thread.sleep(1000);
            }

    } catch (AWTException e) { 
        e.printStackTrace(); 
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

Solution

  • If your goal is to simulate user interactions, you MUST use Robot to simulate user mouse events (click in a JTextField for example) before sending key events.

    That way, you will be immune to outside interactions which can grab you focus (desktop notifications, others apps, etc...)