4

I've used the Robot class in java numerous times as a quick workaround on menial tasks. Stopping execution is always a problem (which needs to be numerous times during testing). What I want is a KeyListener that will listen for a key/combination of keys and will stop the program. From my brief readings, it seems you can't embed a key listener without a frame or something of the like in focus. To me, focus means the forefront window. Is this the wrong definition? If this is the correct definition, I can't keep the window in focus because I am crawling around with my robot. How can I solve this problem?

While typing this, I came up with an un-ideal solution of programmatically bringing the window into focus, testing for the keypress, then programmatically bringing it out of focus and continuing. Is this possible? Is there a better way?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Chad
  • 2,335
  • 8
  • 29
  • 45

2 Answers2

2

Do you want a global key listener, something that listens to keys no matter what application has the focus? This is not possible to do with Robot/pure Java.

However, if running on Windows you can do this with JNA. JNA's KeyHook example is a good starting point.

prunge
  • 22,460
  • 3
  • 73
  • 80
1

Well, I'm not too conversant with Java's Robots, but the KeyListener issue may be solvable with Input/Action Maps (Guide here).

Alternatively, you could use a JOptionPane with a confirm message ("Continue Robotting? Y/N") instead of testing for a keypress. Still not the best solution though.

BenCole
  • 2,092
  • 3
  • 17
  • 26