简体   繁体   中英

Key bindings with multiple keys

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

Everything works perfectly, but i noticed that when i press ie 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?

See Motion Using the KeyBoard for a potential solution.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM