问题
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