Java KeyEvents on Mac

两盒软妹~` 提交于 2019-12-11 04:10:03

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/7848486/java-keyevents-on-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!