How to remap a keyboard key using Java Swing?

走远了吗. 提交于 2020-02-06 22:52:36

问题


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


回答1:


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

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



回答2:


Don't really understand the context of your question. But theoretically you could intercept all KeyEvents and then dispatch a different KeyEvent based on your criteria. Global Event Dispatching might give you some ideas.




回答3:


Capture key-events:

java.awt.Toolkit.getDefaultToolkit().addAWTEventListener(myListener, AWTEvent.KEY_EVENT_MASK);

Simulate key press:

java.awt.Robot.keyPress(myKeyCode);


来源:https://stackoverflow.com/questions/1450383/how-to-remap-a-keyboard-key-using-java-swing

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