2008-05-20

Add KeyListener on Java Swing JFrame

Use a code like this

AbstractAction act = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
        //Action that you want to do.
    }
};
getRootPane().getActionMap().put("nameThatYouWant", act);
InputMap im = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
// KeyEvent.VK_F10 or any key that you want.
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "nameThatYouWant");

2 comments:

Marius said...

thanks for the code!

as a remark, you should put at least this into your AbstractAction:
putValue(ACTION_COMMAND_KEY, "actionCommand");

and probably more, see javax.swing.Action doc.
otherwise this action is quite useless as it cannot be identified upon consumption.

Unknown said...

excelente code, thanks!!!