0

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
    }
});
jvdhooft
  • 657
  • 1
  • 12
  • 33
Dim
  • 4,527
  • 15
  • 80
  • 139
  • You may be looking for a [`DocumentListener`](http://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html). – trashgod Aug 06 '13 at 13:39
  • 1
    you can't - keybindings are meant for _specific_ keyStrokes. What do you want to achieve? – kleopatra Aug 06 '13 at 13:59
  • Seems like you wanted to add every key on the keyboard to be mapped with this component. At the same time, you wanted, it to be done with a minimum of code. I hope I am write in describing your situation. Please do replace __cahnhe__ to ___change___, seems like you meant to write the latter, but typed the former :-) – nIcE cOw Aug 06 '13 at 14:07

2 Answers2

2

how can I ("cahnhe") this code to accept any key (not only F5) and print the key?

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

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.
        }
    }
}
Elist
  • 5,313
  • 3
  • 35
  • 73