Search code examples
javamacosswingosx-snow-leopard

Java KeyEvents on Mac


I am trying to write a program that uses key events to activate a method. The code works on Windows machines but when transered to Mac it does no respond to my "Spacebar" being pressed. I presume this is to do with the different key codes used.

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
        System.out.println("SPACEBAR");
        grid.stepGame();

    }
}

Any ideas how i can get this working on Mac?

Edit - The problem has been solved using the answer below - For note though it seems that on Mac the Frame never automatically regains focus, hence why the keylistener doesn't work is another JComponent is activated.


Solution

  • I'm uncertain as to your particular issue but it's a good bet that if you switch to using key bindings instead of key listeners your issue would disapear. From the Java Tutorials site:

    Note: To define special reactions to particular keys, use key bindings instead of a key listener.

    As an example

    // Component that you want listening to your key
    JComponent component = ...;
    component.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
                            "actionMapKey");
    component.getActionMap().put("actionMapKey",
                             someAction);