Adding KeyListener to frame
Hi all
I'm trying to add a keylistener to my class. I've extended JFrame so I assumed this would work
addKeyListener(this);
Alas, it doesn't, nor does it work if I add it to my content pane
getContentPane().addKeyListener(this);
I've had a look through previous posts but not found anything of much help. I've declared all the necessary methods the KeyListener interface requires, any ideas anyone?
Thanks
Difficult? Not the second time you do it, but the framework is general
so there are a couple steps to it:
1. Define an action
2. Get the appropriate InputMap and map a keystroke to an actionMapKey.
2. Get the ActionMap and map that key to your action.
In my demo I map ctrl+Q to a sample action. Since it fires WHEN_IN_FOCUSED_WINDOW,
there is no need to make the component focusable.
import java.awt.event.*;
import javax.swing.*;
class ExampleAction extends AbstractAction {
public ExampleAction() {
super("ExampleAction");
}
public void actionPerformed(ActionEvent evt) {
System.out.println("ExampleAction.actionPerformed");
}
}
public class KeyboardMappingExample extends JPanel {
public KeyboardMappingExample() {
KeyStroke ks = KeyStroke.getKeyStroke("ctrl Q");
Action action = new ExampleAction();
Object name = action.getValue(Action.NAME);
InputMap im = this.getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = this.getActionMap();
im.put(ks, name);
am.put(name, action);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame f = new JFrame("ExampleAction");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new KeyboardMappingExample());
f.setSize(400,400);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
> I've had a look through previous posts but not found anything of much help
Swing related questions should be posted in the Swing forum.
Read the answer I just posted here:
http://forum.java.sun.com/thread.jspa?threadID=5144784&tstart=0
Thats why questions should be posted in the correct forum. So we don't waste time answering the same question over and over. It is your responsibility to actually search the "correct" forum before posting to see if the question has been asked before.