Listening for input without focus in Java

Alex picture Alex · May 23, 2009 · Viewed 35.8k times · Source

I'm making a small program in Java using the Robot class. The program takes over the mouse. while in the course of debugging if it starts acting in a way that I don't want it's hard to quit the program, since I can't move the mouse over to the terminate button in eclipse, and I can't use hotkeys to hit it because the mouse is constant clicking in another window, giving that window focus instead.

What I'd like to do is just hook up a keylistener so that when I hit q I can quit the program, but the only way I know how to do this involves making a window, and that window needs focus to capture the input. Is there a way to listen for keyboard or mouse input from anywhere, regardless of what has focus?

Answer

MasterID picture MasterID · Oct 20, 2013

There is a library that does the hard work for you: https://github.com/kwhat/jnativehook