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?

Simon Dugré
  • 17,980
  • 11
  • 57
  • 73
Gadoya
  • 137
  • 1
  • 3
  • 7
  • Dynamically generating Swing Components? We can add shortcuts to a component but not application wide - `component.getInputMap().put(aKeyStroke, aCommand);` – Chan Jul 18 '12 at 02:27

4 Answers4

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);
                }
            }
        }
    };
Community
  • 1
  • 1
Chan
  • 2,601
  • 6
  • 28
  • 45
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.

Wolfram
  • 8,044
  • 3
  • 45
  • 66
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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045