Mac上的Java KeyEvent [英] Java KeyEvents on Mac

查看:284
本文介绍了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.

推荐答案

我不确定您的特定问题,但是如果您转而使用

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.

例如

// 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆