本文介绍了Mac上的Java KeyEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个使用键事件来激活方法的程序.该代码可在Windows计算机上运行,​​但是当转换为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();

    }
}

有什么想法可以使它在Mac上运行吗?

Any ideas how i can get this working on Mac?

编辑-使用下面的答案已解决了该问题-需要注意的是,尽管在Mac上看来Frame永远不会自动重新获得焦点,因此为什么侦听器不起作用是另一个JComponent被激活了.

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.

推荐答案

我不确定您的特定问题,但是如果您转而使用键绑定,而不是键侦听器,您的问题就会消失.从Java教程站点:

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:

例如

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

这篇关于Mac上的Java KeyEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:04
查看更多