具有多个键的键绑定 [英] Key bindings with multiple keys

查看:143
本文介绍了具有多个键的键绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码将键盘键绑定到自定义操作,而不使用 KeyListener

I'm using this code to bind keyboard keys to custom actions without using the KeyListener:

Action left = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("pressed left key");
    }
};

Action right = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("pressed right key");
    }
};

Action space = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("pressed space key");
    }
};

myJPanel.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "pressedLeft");
myJPanel.getInputMap().put(KeyStroke.getKeyStroke("A"), "pressedLeft");
myJPanel.getActionMap().put("pressedLeft", left);

myJPanel.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "pressedRight");
myJPanel.getInputMap().put(KeyStroke.getKeyStroke("D"), "pressedRight");
myJPanel.getActionMap().put("pressedRight", right);

myJPanel.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "pressedSpace");
myJPanel.getActionMap().put("pressedSpace", space);

一切都很完美,但我注意到当我按下 SPACE 时持有 A 动作不再被触发,如果同时触发两个按键的事件,那将会很棒。

Everything works perfectly, but i noticed that when i press i.e. SPACE while holding A, the left action isn't fired anymore, it would be great if events for both pressed keys are fired.

有没有办法使用带键组合的键绑定?

Is there any way to use key bindings with key combinations?

推荐答案

参见使用KeyBoard运动可能的解决方案。

See Motion Using the KeyBoard for a potential solution.

仅为按下的最后一个键生成一个事件,因此您需要手动跟踪已按下的任何其他键(并保持手动模拟触发事件)。无论您使用键绑定还是KeyListener都是如此。

An event is only generated for the last key pressed so you need to manually keep track of any other keys that have been pressed (and keep manually simulate firing the event). This is true whether you use key bindings or a KeyListener.

这篇关于具有多个键的键绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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