如何使用Java Swing重新映射键盘键? [英] How to remap a keyboard key using Java Swing?

查看:103
本文介绍了如何使用Java Swing重新映射键盘键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java重新映射键盘上的按键,以便赋予按键新的含义?

How do I remap a key on the keyboard using Java so that I can give the key a new meaning?

推荐答案

如果我理解这个问题,那就是如何显式定义特定键的行为.这是我实现键盘快捷键的方法-希望它可以回答您的问题.在下面的示例中,我相信您可以将"this"更改为希望明确设置键盘行为的特定组件,从而覆盖其默认行为.我通常是在面板或框架的背景下进行此操作.

If I understand the question, it's how to explicitly define behavior for a specific key. Here's how I do this to implement keyboard shortcuts -- hopefully it answers your question. In my example below, I believe you can change 'this' to be the specific component you wish to explicitly set the keyboard behavior on, overriding its default behavior. I usually do this in the context of a panel or frame.

private void addHotKey(KeyStroke keyStroke, String inputActionKey, Action listener) {
    ActionMap actionMap = this.getActionMap();
    InputMap inputMap = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(keyStroke, inputActionKey);
    actionMap.put(inputActionKey, listener);
}

inputActionKey只是用于映射操作的任意键字符串.调用此方法以侦听DEL键的示例:

The inputActionKey is just an arbitrary key string to use for mapping the action. An example of invoking this method to listen for the DEL key:

    KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
    Action listener = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            // delete something...
        }
    };
    addHotKey(keyStroke, "MainWindowDEL", listener);

这篇关于如何使用Java Swing重新映射键盘键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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