0

So. I got a little problem. Most likey caused because Im very new to java. Anyways, my question is: Why does this not work?

public static void pressKey(KeyEvent key) throws AWTException {
    Robot r = new Robot();
    r.keyPress(KeyEvent.key);
    r.keyRelease(KeyEvent.key);
}

How would I get something like this to work? It would make my life alot easier. thanx in advance

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142

3 Answers3

1

There is no public static field called key in KeyEvent that's why

//just pass they argument to your method as argument to those methods
r.keyPress(key);
r.keyRelease(key);
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
1

You have to use

 public static void pressKey(int key) throws AWTException {
    Robot r = new Robot();
    r.keyPress(key);
    r.keyRelease(key);
}

for it to work

thedayofcondor
  • 3,860
  • 1
  • 19
  • 28
  • The method keyPress(int) in the type Robot is not applicable for the arguments (KeyEvent) – user1591340 Nov 04 '12 at 23:17
  • Now if I use `pressKey(KeyEvent.VK_C);` I get `The method pressKey(KeyEvent) in the type Main is not applicable for the arguments (int)` – user1591340 Nov 05 '12 at 00:15
0

That 'key' variable is an integer. A KeyEvent is just an easy-to-remeber way to use it, but both are integers.

It means the method uses an integer, not a KeyEvent.

Let's say we have the following method:

public static void press(int event) throws AWTException {
    Robot bot = new Robot();
    bot.keyPress(event);
    bot.keyRelease(event);
}

It could be called by two ways: the KeyEvent and an integer. All the same (don't forget to add a 'throws' statement or a 'try/catch'):

press(KeyEvent.VK_SLASH);

Or:

press(46);

If I'm right, both would send a slash (correct me if I'm wrong). But KeyEvents are way easier.

Also, keep in mind that not all keyboards have the same layout. Depending on the key, a completely different key would be sent, or worse, the robot would throw an IllegalArgumentException. I recommend you use Alt codes for characters that are not letters/numbers.

borges
  • 371
  • 4
  • 12