java中的自定义键盘快捷键 [英] Custom keyboard shortcut in java

查看:357
本文介绍了java中的自定义键盘快捷键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个java swing应用程序。我想添加键盘快捷键,例如 CTRL    + H 。这应该执行jButton1在单击时执行的相同操作。

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.

即使jButton1没有聚焦,此快捷方式也应该以相同的方式运行。

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

我尝试使用KeyEventDispatcher,但它似乎对我不起作用。还有别的办法吗?

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

推荐答案

好的 - 首先我认为没有办法在Java Swing中设置应用程序范围的快捷方式(请参阅此问题)。但对于一个组件,它是可能的。

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.

你必须为<$ c $使用创建一个 Action C>的KeyStroke 。但对于Windows,我发现这个库非常有帮助

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

这篇关于java中的自定义键盘快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆