Reputation: 55
I've been trying to learn how to use Key Binding in Java. This is what I have so far but it doesn't seem to be working. When I press 'w' it's supposed to print "Hello!". However pressing 'w' does nothing.
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Space extends JPanel {
public static void createAndShowUI() {
JFrame frame = new JFrame("Space");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Space());
frame.pack();
frame.setVisible(true);
Action wKey = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
};
};
InputMap im = frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap am = frame.getRootPane().getActionMap();
im.put(KeyStroke.getKeyStroke("w"),"doSomething");
am.put("doSomething", wKey);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowUI();
}
});
}}
Thanks in advance!
Upvotes: 1
Views: 453
Reputation: 324108
1) You are changing the wrong InputMap:
//InputMap im = frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
InputMap im = frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
2) You are creating the KeyStroke incorrectly. The string should contain a value found when using KeyEvent_VK?.
So in your case you could use "W", which would map to KeyEvent.VK_W. This will map to keyPressed for "w".
You can also do the binding for keyTyped events:
im.put(KeyStroke.getKeyStroke('w'),"doSomething"); // or
im.put(KeyStroke.getKeyStroke("typed w"),"doSomething");
Upvotes: 3