java - Keylistener not working for JPanel -
i trying when 1 of arrow keys pressed using keylistener in jpanel class. here code:
public class testpanel extends jpanel implements keylistener{ public testpanel(){ this.addkeylistener(this); this.setfocusable(true); this.requestfocusinwindow(); } public void keypressed(keyevent e) { if (e.getkeycode() == keyevent.vk_right) { system.out.println("right"); } if (e.getkeycode() == keyevent.vk_left) { system.out.println("left"); } } public void keytyped(keyevent e) {} public void keyreleased(keyevent e) {} }
my main method adds new instance of panel frame , displays it. need add keylistener jframe? in case, difficult , inefficient, make work jpanel if possible. know doing wrong?
edit: key bindings code not work either:
public class gamepanel extends jpanel implements actionlistener{ //constructor public gamepanel(){ setupkeybinding(); this.setfocusable(true); this.requestfocusinwindow(); } private void setupkeybinding() { int condition = jcomponent.when_in_focused_window; inputmap inmap = getinputmap(condition); actionmap actmap = getactionmap(); inmap.put(keystroke.getkeystroke(keyevent.vk_left, 0), "left"); actmap.put("left", new leftaction()); } private class leftaction extends abstractaction { public void actionperformed(actionevent e) { system.out.println("test"); } } public void actionperformed(actionevent e) { //some other game info } }
can tell me why doesnt work either? (my second action listener other stuff needed game)
if search problem, you'll see asked , has been solved many times.
- keylisteners need on focused component work. 1 solution give component focus after first making focusable.
- better long shot use key bindings. google tutorial on this.
please have @ answer this question more on this, including many of gory details.
Comments
Post a Comment