A few keystrokes with dispatcher

How do I change the dispatcher class to catch a few keystrokes? 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; } } 
+4
source share
2 answers

I solved my problem:

 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; } } 
+4
source

If the user types N+J , I want to print NJ .

Attempting to press N and J simultaneously will cause one KeyEvent to arrive after another. One approach is to create an enum Key similar to this one . Using EnumSet , create Set current . As KEY_PRESSED events KEY_PRESSED update current to include the current keys pressed plus a new one; as KEY_RELEASED events, update current to exclude a new one. The current.equals() method will allow you to compare with the predefined key states used in your game. Note that EnumSet instances are immutable, but effectively small for a reasonable number of keys.

+3
source

All Articles