15

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.

Chris
  • 1,343
  • 3
  • 11
  • 18
  • 2
    In what? Swing? the console? an applet? GWT? – Roddy of the Frozen Peas Jul 11 '12 at 22:29
  • What I am hoping to achieve is mouse over somewhere and then press a key and it saves the mouses pos. Then it goes back to it and clicks there. – Chris Jul 11 '12 at 22:31
  • The `Robot` class from my answer even allows you to move your mouse. And the [`MouseInfo`](http://docs.oracle.com/javase/7/docs/api/java/awt/MouseInfo.html) class is good for remembering the mouse position, too. Good luck! – Petr Janeček Jul 11 '12 at 22:37

2 Answers2

23

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);
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • Here's another question. How would I take a single character like a and convert it to a keycode? – Chris Jul 11 '12 at 22:38
  • 1
    @Sauce If you mean what I mean, then I've used [this question](http://stackoverflow.com/questions/1248510/convert-string-to-keyevents). – Petr Janeček Jul 11 '12 at 22:41
  • But sometimes you can find that roboted key press happens outside your application - in another, unwanted one, if you switch between them. – Zon Jul 16 '13 at 10:24
  • @Zon Yes, that's absolutely true and it is a thing one _must_ be aware of. In that case, you probably don't want to press the virtual key programatically, but create a key press event programatically - for example for you Swing app or for whatever reason. Both solutions have their usages. – Petr Janeček Jul 16 '13 at 12:23
0
Action act = new Action(driver);
act.sendkeys(Keys.ENTER).build().perform();
Diligent Key Presser
  • 4,183
  • 4
  • 26
  • 34