There are a lot of topics on how to capture keystrokes in Java Swing, but I'd like to ask about the best practice. For example, I have a window in which I wish to listen to a keystroke of either F1
or Command-P
on a Mac (or CTRL-P
on a PC).
Reading The official Javadoc for KeyEvent, it seems that it is a better practice to use Key Typed
events rather than Key Pressed
or Key Released
events, because they are higher-level. This makes sense to me, and I've even found that in order to make sure the program is platform-agnostic, I have to specify a keystroke object thusly:
private KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
This should allow for capturing of either the Command
accelerator key on a Mac, and the CTRL
accelerator key on a PC. (I hope I'm using those terms correctly.) So now that I have a KeyStroke
object, how do I go about checking it against a KeyEvent
object in my KeyListener
? And throwing a check for an F1
key event as well only complicates the matter further, though hopefully not too much.
Suggestions?
So now that I have a KeyStroke object, how do I go about checking it against a KeyEvent object in my KeyListener?
You don't use a KeyListener. Swing was designed to be used with Key Bindings
.
Check out Key Bindings which contains a program to list the default bindings of each Swing component. It also give some example of how you might create your own ey Bindings
. It also contains a link to the Swing tutorial on Key Bindings which explains the whole process in more detail