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?
Try this:
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
//do something
}
}