Search code examples
javaawtrobot

java robot keypress does not work


so I'm facing a problem which is when I use this code :

code was updated

        int x = 530;
        int y = 135;
        Robot r = new Robot();
        r.mouseMove(x, y);
        r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
        r.keyPress(KeyEvent.VK_T);
        r.keyPress(KeyEvent.VK_E);
        r.keyPress(KeyEvent.VK_S);          
        r.keyPress(KeyEvent.VK_T);

the program types "test" in eclipse, and so I have done some search and found people with similar issues and after they have compiled it to jar it worked fine, and so that is what I did , but after compiling it, the mouse is moving fine but the program does not type anything.


Solution

  • I don't know where you send the clicks and the keystrokes to, so I can't be sure what the problem is, but my guess as to why the code is not working as intended is that you never release the mouse button and the keys. Robot.mousePress(int) only presses the mouse button down, it doesn't release it, you'd have to call Robot.mouseRelease(int) (as stated in the documentation). The same applies to keystrokes. Also, InputEvent.BUTTON1_MASK is deprecated, the documentation recommends to use InputEvent.BUTTON1_DOWN_MASK instead.