java - How do you reference a button inside of its actionlistener? -
i'm starting used listeners still kind of new working them. need reference button inside of actionlistener text of button. code want is:
for(int = 0; i<48; ++i){ button[i] = new jbutton(""); contentpane.add(button[i]); button[i].addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { x_marks_the_spot(); if(button[i].gettext().equals("x")){ increase_hit(); } else{ increase_miss(); } } });
obviously can't because [i] doesn't exist in anon portion of code. sure there way getting source, can't think of it.
obviously can't because
[i]
doesn't exist in anon portion of code.
you copying i
final
variable:
// make final copy of loop variable before making listener final tmpi = i; ... // use final variable instead of `i` inside listener if(button[tmpi].gettext().equals("x")){
however, not efficient way of doing it, because each button need own listener object, reference tmpi
stored inside code.
you can create single actionlistener
object, , share among buttons, this:
actionlistener listener = new actionlistener() { public void actionperformed(actionevent e) { x_marks_the_spot(); jbutton sender = (jbutton)e.getsource(); if(sender.gettext().equals("x")){ increase_hit(); } else{ increase_miss(); } } }; for(int = 0; i<48; ++i){ button[i] = new jbutton(""); contentpane.add(button[i]); button[i].addactionlistener(listener); }
Comments
Post a Comment