Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top