Reputation: 4807
How can I change this code to accept any key (not only F5) and print the key?
component.getRootPane().getInputMap(JRootPane.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "F5 Pressed");
component.getRootPane().getActionMap().put("F5 Pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// Code here
}
});
Upvotes: 0
Views: 112
Reputation: 5533
Use KeyboardFocusManager
to register a KeyEventDispatcher
:
KeboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
if (yourComponent.hasFocus && ke.getID == KeyEvent.KEY_TYPED) {
// Your code here
// Use ke.getKeyChar() to detect which key was pressed.
}
}
}
Upvotes: 1
Reputation: 109815
how can I ("cahnhe") this code to accept any key (not only F5) and print the key?
sorry this question doesn't make me some sence, in this form
basic is described in tutorial,
component.getRootPane()
could be valid only for JFrame
, JDialog
, JWindow
, practically only JFrame
has accesible RootPane
otherwise to add Input/ActionMap
to the desired JComponent
directly
Upvotes: 2