java - KeyListener wont focus -
i'm new java please forgive me asking help, after 4 hours of searching solution i'm getting desperate.
i'm setting game , want implement key controls. tried via keylistener
, keyeventdispatcher
can't work. keylistener
won't react. think method supposed use has focus.
here's code:
public class sins extends jframe implements keyeventdispatcher { public boolean dispatchkeyevent(keyevent e) { if (e.getid() == keyevent.key_pressed ) { if(keyevent.vk_up == e.getid()){ system.exit(0); } } else if (e.getid() == keyevent.key_released) { if(keyevent.vk_up == e.getid()){ system.exit(0); } } else if (e.getid() == keyevent.key_typed) { if(keyevent.vk_up == e.getid()){ system.exit(0); } } return false; }
and here method supposed working at:
public void run() { setfocusable(true); backgroundgraphics = (graphics2d) background.getgraphics(); long fpswait = (long) (1.0 / 30 * 1000); requestfocusinwindow(); main: while (isrunning==true) { long renderstart = system.nanotime(); keyboardfocusmanager manager = keyboardfocusmanager.getcurrentkeyboardfocusmanager(); manager.addkeyeventdispatcher(this); x++; requestfocusinwindow(); // update graphics { graphics2d bg = getbuffer(); if (isrunning == false) { break main; } rendergame(backgroundgraphics); // calls draw method if (scale != 1) { bg.drawimage(background, 0, 0, width * scale, height * scale, 0, 0, width, height, null); } else { bg.drawimage(background, 0, 0, null); } bg.dispose(); requestfocusinwindow(); this.requestfocus(); if(x ==5000){ isrunning=false; } } while (!updatescreen()); // better fps limiting here long rendertime = (system.nanotime() - renderstart) / 10000; try { thread.sleep(math.max(0, fpswait - rendertime)); } catch (interruptedexception e) { thread.interrupted(); break; } rendertime = (system.nanotime() - renderstart) / 10000; } this.dispose(); system.exit(0); }
the program closing after counting 5000. test purposes i'm trying close via button won't close way. appreciate help, said i'm new java.
the first problem facing keylistener
know , documented (here on especially). keylistener
on respond if component attached focusable , has keyboard focus. think of text field, when doesn't have focus, won't update.
your second problem using keyboardfocusmanager
, overkill problem.
instead, should make use of [key bindings] api, simpler having monitor keyboardfocusmanager
, more robust keylisteners
Comments
Post a Comment