Search code examples
javaswingkey-bindings

Java Swing get input


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
    }
});

Solution

  • 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.
            }
        }
    }