Is there a way to set a button key event in Java so that Alt does not have to be pressed. For example, when this is used setMnemonic(KeyEvent.VK_DELETE)
it is required for Alt + Delete to be pressed in the application. How can I get around this? Thanks.
Asked
Active
Viewed 1.4k times
4
2 Answers
11
I would take a look at the key bindings tutorial. You can specify any KeyStroke
to perform any Action
.

Jeffrey
- 44,417
- 8
- 90
- 141
-1
Create a KeyListener, or extend a KeyAdapter. Like this:
private class MnemonicWorkaround extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
if(c == KeyEvent.VK_ENTER){
// do something.
}
}
}
Then add it using component.addKeyListener(new MnemonicWorkaround());

rtheunissen
- 7,347
- 5
- 34
- 65
-
Just be wary of which component to add the listener to, and whether it has / maintains focus. – rtheunissen Jan 08 '12 at 04:34
-
1-1 for keyListener, it's useless here (as it is nearly always) – kleopatra Jan 08 '12 at 12:19
-
Why is it nearly always useless? – rtheunissen Jan 08 '12 at 12:22
-
1because they are so low-level that they can't do what is required ;-) The general rule is to go for the highest abstraction available (which are keybindings in this context) – kleopatra Jan 08 '12 at 12:42