Allow user to redefine hotkeys for Swing during runtime Java -


i have java application contains lot of features, , make life easier user, have set numerous mnemonics , accelerators. instance, have jmenuitem allows user save state of application, witht following code:

jmenuitem saveitem = new jmenuitem("save"); saveitem.setmnemonic('s'); saveitem.setaccelerator(keystroke.getkeystroke(keyevent.vk_s, inputevent.ctrl_mask));  

this works desired, give user option change hot keys. while ctrl + s seem obvious hot key stick with, there many features use these short cuts, , picked save example.

i have jbutton have arranged testing purposes allows user enter in new shortcut when clicked. thinking try , capture keys user holds down (inputevent) , presses (keyevent). though might smart force use of inputmask avoid complications in text fields , like.

what wondering is: best way capture new input user enters? have looked information regarding keybindings , right job, main issue see capturing keys , saving them.

sounds need setup keylistener. when user presses/releases key, triggers keyevent can retrieve main key pressed (e.g. s) , mask/modifiers (e.g. ctrl+shift).

from there can create keystroke object , set new accelerator of menu.

public void keyreleased(keyevent e){    keystroke ks = keystroke.getkeystroke(e.getkeycode(), e.getmodifiers());    menuitem.setaccelerator(ks); } 

the thing want key listener removed right after key released event, avoid multiple keystrokes captured. have kind of logic:

jbutton capturekeybutton = new jbutton("capture key"); jlabel capturetext = new jlabel(""); keylistener keylistener = new keyadapter(){    public void keyreleased(keyevent e){        keystroke ks = keystroke.getkeystroke(e.getkeycode(), e.getmodifiers());        menuitem.setaccelerator(ks);        capturetext.settext("key captured: "+ks.tostring());        capturekeybutton.removekeylistener(this);    } }; actionlistener buttonclicked = new actionlistener(){    public void actionperformed(actionevent e){        capturekeybutton.addkeylistener(keylistener);        capturetext.settext("please type menu shortcut");    } }; capturekeybutton.addactionlistener(buttonclicked); 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -