This is my first test at making a key event dispatcher. Some of the code is unnecessary if one is interested in separating lower and upper cases, however I want to treat them as the same. Hence my wonderfully named method keyToLowerCaseIfUpperCase(char c)
. I also want to lock the key if it has been pressed untill it is released by the user. To run an event twice the user first needs to release the key.
First of it checks if the key is in [A...Z], if so it returns the corresponding lower key. If not it will keep the key intact. Then I check whetever a key was pressed or not pressed, if it was pressed it will check if that specific key actually can be pressed (using my lock). If it was a key release it will simply release the lock of that key.
import java.awt.KeyEventDispatcher;
import java.awt.event.KeyEvent;
import java.util.HashMap;
public class KeyBindManager implements KeyEventDispatcher
{
private HashMap<String, Boolean> keyPresses = new HashMap<>();
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
String pressed = keyToLowerCaseIfUpperCase(e.getKeyChar())+"";
if (e.getID() == KeyEvent.KEY_PRESSED) {
if (keyPresses.get(pressed) != null && keyPresses.get(pressed).booleanValue()) {
return false;
}
keyPresses.put(pressed, new Boolean(true));
switch (keyToLowerCaseIfUpperCase(e.getKeyChar())) {
case 'a': System.out.println("D"); break; // these are just two test cases
case 'b': System.out.println("E"); break;
default: break;
}
} else if (e.getID() == KeyEvent.KEY_RELEASED){
keyPresses.put(pressed, new Boolean(false));
}
return false;
}
private char keyToLowerCaseIfUpperCase (char c) {
if (c >= 'A' && c <= 'Z') {
c = Character.toLowerCase(c);
}
return c;
}
}
Please tell me this can be done in a more clean approach than what I've accomplished. I don't like the looks of my code very much at all. For now, it gets the job done.
To emphasize, it is the first draft for it. Every criticism is welcome.
keyChar
, instead, use thekeyCode
. It's possible that until the key is released that thekeyChar
won't be interrupted. ThekeyCode
s are also independent of the modifier keys (shift, alt, ctrl, meta)... – MadProgrammer Feb 15 at 23:38Graphics
. – Emz Feb 15 at 23:52JComponent
somewhere (I'm just throwing fuel on the fire :)) – MadProgrammer Feb 16 at 0:00