Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Press a key with Java

Tags:

java

I was wondering if it is possible to press a key with Java. Not quite sure how to approach this. There must be some type of class that has like sendKeyPress(); or something.

like image 209
Chris Avatar asked Jul 11 '12 22:07

Chris


People also ask

What does keyPressed do in Java?

In Java, there are three types of KeyEvent. The types correspond to pressing a key, releasing a key, and typing a character. The keyPressed method is called when the user presses a key, the keyReleased method is called when the user releases a key, and the keyTyped method is called when the user types a character.


1 Answers

You can do it easily with the Robot class. That just virtually presses the button, with no special targeting or anything.

For example, to press Enter:

Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
like image 74
Petr Janeček Avatar answered Sep 21 '22 05:09

Petr Janeček