Custom keyboard shortcut in java

半腔热情 提交于 2019-12-06 01:59:07
Chan

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

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.

trashgod

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!