Something you can do is implement the KeyListener
interface and give states to all the keys you're interested in.
If you're interested in checking if the arrow keys are depressed upon a screenshot, for instance, you can implement this KeyListener
interface and override keyPressed()
and keyReleased()
methods and set the state for those keys you are interested in to keyPressed
or keyReleased
. Depending on the event. That way, when the screenshot occurs, you can just read the state of those keys
If you need this solution to be global, regardless of application focus, you could write a small hook in C that you can integrate with Java Native Interface to listen for key events. Java doesn't let you listen to key events without you attaching the listener to a component and that component having focus. Have a look at JNativeHook.
If you just need it when your application has focus but on every component you could inelegantly attach the listener to all your components or you could write your own custom KeyEventDispatcher and register it on the KeyBoardFocusManager. That way, as long as your application has focus, regardless of component that has specific focus, you could catch all keyboard events. See:
public class YourFrame extends JFrame {
public YourFrame() {
// Finish all your layout and add your components
//
// Get the KeyboardFocusManager and register your custom dispatcher
KeyboardFocusManager m = KeyboardFocusManager.getCurrentKeyboardFocusManager();
m.addKeyEventDispatcher(new YourDispatcher());
}
private class YourDispatcher implements KeyEventDispatcher {
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_TYPED) {
// Do something to change the state of the key
} else if (e.getID() == KeyEvent.KEY_PRESSED) {
// Do something else
}
return false;
}
}
public static void main(String[] args) {
YourFrame yF = new YourFrame();
yF.pack();
yF.setVisible(true);
}
}