java - Many jbuttons with the same onkeypress function -
i have many jbuttons (around 50+) can clicked.
after clicking 1 program check key inputs , set button text pressed key.
instead of copy pasting 50 codeblocks each onkeypressed , onclick event of 1 button wanted use function in each event.
my code far (reduced):
private jbutton attackmovebtn = new jbutton(); private boolean isalreadyclicked = false; private void attackmovebtnkeypressed(java.awt.event.keyevent evt) { if(attackmovebtn.gettext().equals(strings.sethotkey)){ isalreadyclicked = false; attackmovebtn.settext(string.valueof(evt.getkeychar())); } } private void attackmovebtnmouseclicked(java.awt.event.mouseevent evt) { if(evt.getbutton() == 3){ isalreadyclicked = false; attackmovebtn.settext(""); }else{ if(!isalreadyclicked){ isalreadyclicked = true; attackmovebtn.settext(strings.sethotkey); }else{ isalreadyclicked = false; attackmovebtn.settext("mouse "+evt.getbutton()); } } }
the thing change next button jbutton (attackmovebtn become movebtn example)
i tried use string compname = evt.getcomponent().getname();
retrieve name of button pressed cannot use "attackmovebtn".settext()
because dynamic var names not supported java.
is there way button pressed? call function buttonobject parameter myonkeypressfunction(jbutton mybutton)
my question how can dynamic variable names or if approach wrong , should use different pattern.
"is there way button pressed? call function buttonobject parameter myonkeypressfunction(jbutton mybutton)"
just use getsource
of event returns object
, cast jbutton
it
jbutton button = (jbutton)evt.getsource(); myonkeypressfunction(button);
fyi, buttons used actionlistener
to. if using gui editor tool, when right click on button design view, select, event->action->actionperformed
, actionlistener
added you.
"i using netbeans graphic editor build gui (i suck @ gui programming tbh)"
i suggest ditch builder tool , go through tutorial , learn hand code first. go through creating guis swing.
Comments
Post a Comment