Search code examples
javaswingawtkeyevent

Multiple key presses with dispatcher


How should i modify my dispatcher class in order to catch multiple key presses? For now i just want to print them...

class MyDispatcher implements KeyEventDispatcher {
public boolean dispatchKeyEvent(KeyEvent e) {

if (e.getID() == KeyEvent.KEY_PRESSED) {
   System.out.println(e.getKeyChar());

} 

return false;
}
}

Solution

  • I solved my problem with:

    class MyDispatcher implements KeyEventDispatcher {
    ArrayList<String>typedKeys = new ArrayList<String>();
    public boolean dispatchKeyEvent(KeyEvent e) {
    
    if (e.getID() == KeyEvent.KEY_PRESSED) 
        typedKeys.add(""+e.getKeyChar());
    
    if (e.getID() == KeyEvent.KEY_RELEASED) {
        String str = typedKeys+"";
        System.out.println(str.substring(1,str.length()-1).replaceAll(", ",""));
        typedKeys.clear();
     } 
    
    return false;
    }
    
    }