views:

395

answers:

3

how to remap a key in keyboard using java so that i could give new meaning to a key

A: 

Capture key-events:

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

Simulate key press:

java.awt.Robot.keyPress(myKeyCode);
Witek
and what will you do with that keypress once you capture it?
kdgregory
Get the typed key and remap it to your own. Isn't this what was asked for?
Witek
A: 

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.

camickr
A: 

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);
Chris B.