java - Keylistener on jpanel won't work -


this question has answer here:

i'm trying add keylistener jpanel won't work after this:

put.setfocusable(true);     put.requestfocusinwindow();     keyboardhandler keyhandler=new keyboardhandler();     put.addkeylistener(keyhandler); } private class keyboardhandler implements keylistener{     public void keypressed(keyevent e) {     system.out.println("ovde zzz");     if(e.getkeycode()==17) ctrl=true;         if(e.getkeycode()==90) z=true;         if(ctrl && z){             if (undobrojac==0) joptionpane.showmessagedialog(null, "you can't undo that");             else{                 undobrojac--;                 put.setundo(undobrojac);             }         }  }  public void keyreleased(keyevent e){     if (e.getkeycode()==17) ctrl = false;     if (e.getkeycode()==90) z = false; }      public void keytyped(keyevent e) {} } 

i'm trying add ctrl+z doesn't work.

several helpful comments suggest using key bindings. shown here, particularly easy specify keyevent.vk_z accelerator_key in context of action. if undoing changes text component, see how write undoable edit listener; textcomponentdemo cited there illustrates typical undoaction.


Comments