Reputation: 2563
I'd like to have a KeyListener on a JComponent in Swing that reacts on press and release of the ctrl key. This a naive, but suboptimal solution (it reacts on every keypress, not only on press/release of the ctrl key:
new KeyAdapater() {
public void keyPressed(KeyEvent e) {
if (e.isControlDown()) {
//do something
}
}
public void keyReleased(KeyEvent e) {
if (!e.isControlDown()) {
//do something other
}
}
}
What is a better approach to only trigger, when the ctrl key itself is pressed or released?
Upvotes: 0
Views: 3171
Reputation: 17971
IMHO using Key bindings is a more flexible and reliable approach that brings with these benefits:
WHEN_FOCUSED
, WHEN_IN_FOCUSED_WINDOW
, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
Having said that, we can create KeyStrokes
like follows:
KeyStroke controlKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL, 0);
And we can even specify that the key stroke will be triggered on a key release event:
KeyStroke controlReleasedKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL, 0, true);
Note: 0
means no modifiers and true
is a flag indicating the key stroke represents a key release event. See the API for more details.
See also this topic: Key bindings vs. key listeners in Java, and How to Use Key Bindings tutorial
Upvotes: 4
Reputation: 4065
Try this:
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
//do something
}
}
Upvotes: 3