24 June 2009

Key bindings is sometimes to prefer over KeyListener

In Java (Swing) there are KeyListener:s and key bindins. KeyListerner is the classical way of catching events from the keyboard. But inn some situations the key bindings feature is preferred:

  • If you want to catch (only) the CTRL key

  • If you want to catch keys regardles of where the user has focus


For example if you are developing a tetris game this code can be used to get the Left arrow key:
        getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
getActionMap().put("left", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
engine.moveBrickLeft();
}
});


To catch the control key use KeyStroke.getKeyStroke("ctrl pressed CONTROL") and KeyStroke.getKeyStroke("released CONTROL")

More information at http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html

No comments:

Post a Comment