How to use Key Bindings instead of Key Listeners

后端 未结 4 2090
渐次进展
渐次进展 2020-11-22 03:39

I\'m using KeyListeners in my code (game or otherwise) as the way for my on-screen objects to react to user key input. Here is my code:

public class MyGame e         


        
4条回答
  •  無奈伤痛
    2020-11-22 04:29

    Here is an easyway that would not require you to read hundreds of lines of code just learn a few lines long trick.

    declare a new JLabel and add it to your JFrame (I didn't test it in other components)

    private static JLabel listener= new JLabel(); 
    

    The focus needs to stay on this for the keys to work though.

    In constructor :

    add(listener);
    

    Use this method:

    OLD METHOD:

     private void setKeyBinding(String keyString, AbstractAction action) {
            listener.getInputMap().put(KeyStroke.getKeyStroke(keyString), keyString);
            listener.getActionMap().put(keyString, action);
        }
    

    KeyString must be written properly. It is not typesafe and you must consult the official list to learn what is the keyString(it is not an official term) for each button.

    NEW METHOD

    private void setKeyBinding(int keyCode, AbstractAction action) {
        int modifier = 0;
        switch (keyCode) {
            case KeyEvent.VK_CONTROL:
                modifier = InputEvent.CTRL_DOWN_MASK;
                break;
            case KeyEvent.VK_SHIFT:
                modifier = InputEvent.SHIFT_DOWN_MASK;
                break;
            case KeyEvent.VK_ALT:
                modifier = InputEvent.ALT_DOWN_MASK;
                break;
    
        }
    
        listener.getInputMap().put(KeyStroke.getKeyStroke(keyCode, modifier), keyCode);
        listener.getActionMap().put(keyCode, action);
    }
    

    In this new method you can simply set it using KeyEvent.VK_WHATEVER

    EXAMPLE CALL:

      setKeyBinding(KeyEvent.VK_CONTROL, new AbstractAction() {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("ctrl pressed");
    
            }
        });
    

    Send an anonymous class (or use subclass) of AbstractAction. Override its public void actionPerformed(ActionEvent e) and make it do whatever you want the key to do.

    PROBLEM:

    I couldn't get it running for VK_ALT_GRAPH.

     case KeyEvent.VK_ALT_GRAPH:
                modifier = InputEvent.ALT_GRAPH_DOWN_MASK;
                break;
    

    does not make it work for me for some reason.

提交回复
热议问题