Java can't get KeyListener to work in my GUI -
i making sort of remote control program lego ev3 robot. part irrelevant. made gui , want control robot when press keys. understand have use called keylistener , saw tutorial supposed work.
the gui class code right here. kinda long has keypressed event @ end.
i not sure doing wrong program doesn't detect if key pressed @ all. any.
i appreciate on how make work.
edit:
keymanager=keyboardfocusmanager.getcurrentkeyboardfocusmanager(); keymanager.addkeyeventdispatcher(new keyeventdispatcher() { // up:38 down:40 left:37 right:39 public boolean dispatchkeyevent(keyevent e) { if(e.getid()==keyevent.key_pressed && e.getkeycode()==38){ system.out.println("up"); return true; } if(e.getid()==keyevent.key_released&& e.getkeycode()==38){ system.out.println("released"); return true; } return false; } });
so browsed around , found keyboardfocusmanger sort of working me. testing println. having 1 problem. while hold down key want print once. because key start motor , keep moving until key release stop it.
any ideas on how that?
keylistener
has issues, particularly focus, when of text fields focused, keylistener
won't respond, example.
a better solution make use of key bindings api, allows control level of focus required in order trigger key event. in combination action
api, can define common actions both keys , buttons, example.
take @ how use key bindings , how use actions more details.
ps- i'm jealous , wish luck ;)