Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InputMap for multiple keys

I want to have a custom Tab and Shift+Tab listner in my Swing Application. This works fine for a JTextField textField when the TAB Key is pressed=>

textField.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "Tab");

    textField.getActionMap().put("Tab", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            navigateDown();
        }
    });

But, I want to have the implementation of Shift + Tab and I have used this code :-

textField.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, KeyEvent.VK_TAB), "BackTab");

    textField.getActionMap().put("BackTab", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            navigateUp();
        }
    });

But, this does not works for me. Thanks for your attention.

like image 570
Dev Avatar asked Dec 06 '25 09:12

Dev


1 Answers

Your keystroke is incorrect. The second integer is not a keycode but a modifier.

Try it like this:

textField.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, java.awt.event.InputEvent.SHIFT_DOWN_MASK), "BackTab");

textField.getActionMap().put("BackTab", new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
        navigateUp();
    }
});

See also the JavaDoc on Keystroke.getKeyStroke()

like image 72
David ten Hove Avatar answered Dec 07 '25 21:12

David ten Hove



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!