java - Unresponsive KeyListener for JFrame -


i'm trying implement keylistener jframe. on constructor, i'm using code:

system.out.println("test"); addkeylistener(new keylistener() {     public void keypressed(keyevent e) { system.out.println( "tester"); }      public void keyreleased(keyevent e) { system.out.println("2test2"); }      public void keytyped(keyevent e) { system.out.println("3test3"); } }); 

when run it, test message comes in console. however, when press key, don't of other messages, if keylistener not there.

i thinking because focus not on jframe
, keylistener doesn't receive events. but, i'm pretty sure is.

is there missing?

you must add keylistener every component need. component focus send these events. instance, if have 1 textbox in jframe, textbox has focus. must add keylistener component well.

the process same:

mycomponent.addkeylistener(new keylistener ...); 

note: components aren't focusable jlabel.

for setting them focusable need to:

mycomponent.setfocusable(true); 

Comments