3

I am developing a java swing application. I want to add a keyboard shortcut say CTRL    + H. This should perform the same action performed by jButton1 when clicked.

This shortcut should behave in the same way even when jButton1 is not focused.

I tried with KeyEventDispatcher, but it doesn't seem to be working for me. Is there any other way?

1
  • Dynamically generating Swing Components? We can add shortcuts to a component but not application wide - component.getInputMap().put(aKeyStroke, aCommand);
    – Chan
    Jul 18, 2012 at 2:27

4 Answers 4

3

Ok - First I don't think there is a way to set application wide shortcuts in Java Swing(Refer this question). But for a component it is possible.

You have to use a create an Action for the KeyStroke. But for Windows I found this library very helpful.

    {
        KeyStroke cancelKeyStroke = KeyStroke
                .getKeyStroke((char) KeyEvent.VK_ESCAPE);
        Keymap map = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
        map.addActionForKeyStroke(cancelKeyStroke, cancelKeyAction);
    }
    private static Action cancelKeyAction = new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            Component comp = (Component) ae.getSource();
            Window window = SwingUtilities.windowForComponent(comp);
            if (window instanceof Dialog) {
                window.dispose();
            } else if (comp instanceof JTextComponent
                    && !(comp instanceof JFormattedTextField)) {
                JTextComponent tc = (JTextComponent) comp;
                int end = tc.getSelectionEnd();
                if (tc.getSelectionStart() != end) {
                    tc.setCaretPosition(end);
                }
            }
        }
    };
1

I think the answer to your question can be found here http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#registerKeyboardAction%28java.awt.event.ActionListener,%20java.lang.String,%20javax.swing.KeyStroke,%20int%29

1

You should look into Key Bindings, using classes KeyStroke and InputMap. From Oracle's TextComponentDemo (slightly modified, but still using DefaultEditorKit as example):

// CTRL + H
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.CTRL_MASK);
// bind the keystroke to an object
inputMap.put(key, DefaultEditorKit.backwardAction);

Use them over Key Listeners when you want the event fired even when the component doesn't have the focus:

Key listeners are also difficult if the key binding is to be active when the component doesn't have focus.

1

Instead of using the Control key explicitly as a modifier, use the MASK returned by getMenuShortcutKeyMask() for a better cross-platform user experience. ImageAppis an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.