How to use Key Bindings instead of Key Listeners

后端 未结 4 2091
渐次进展
渐次进展 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:23

    Note: this is not an answer, just a comment with too much code :-)

    Getting keyStrokes via getKeyStroke(String) is the correct way - but needs careful reading of the api doc:

    modifiers := shift | control | ctrl | meta | alt | altGraph
    typedID := typed 
    typedKey := string of length 1 giving Unicode character.
    pressedReleasedID := (pressed | released) key
    key := KeyEvent key code name, i.e. the name following "VK_".
    

    The last line should better be exact name, that is case matters: for the down key the exact key code name is VK_DOWN, so the parameter must be "DOWN" (not "Down" or any other variation of upper/lower case letters)

    Not entirely intuitive (read: had to dig a bit myself) is getting a KeyStroke to a modifier key. Even with proper spelling, the following will not work:

    KeyStroke control = getKeyStroke("CONTROL"); 
    

    Deeper down in the awt event queue, a keyEvent for a single modifier key is created with itself as modifier. To bind to the control key, you need the stroke:

    KeyStroke control = getKeyStroke("ctrl CONTROL"); 
    

提交回复
热议问题