java - Accessing Variable within JButton ActionListener -
this seems simple problem, i'm having lot of trouble figuring out how deal it.
sample scenario:
final int number = 0; jframe frame = new jframe(); frame.setvisible(true); frame.setdefaultcloseoperation(exit_on_close); frame.setsize(400, 400); final jtextarea text = new jtextarea(); frame.add(text, borderlayout.north); jbutton button = new jbutton(number + ""); button.addactionlistener(new actionlistener() { public void actionperformed(actionevent arg0) { number++; // error on line text.settext(number + ""); }}); frame.add(button, borderlayout.south); i have no idea go.
if declared number final, cannot modified value. must remove final modificator.
then, can access variable via:
public class scenario { private int number; public scenario() { jbutton button = new jbutton(number + ""); button.addactionlistener(new actionlistener() { public void actionperformed(actionevent arg0) { scenario.this.number++; text.settext(scenario.this.number + ""); } }); } } the notation "classname.this" allow access object of class in.
keep atention in when use "number" first time, -new jbutton(number)-, can access number directly, because in scenario scope. when use inside actionlistener, in actionlistener scope instead of scenario scope. why cannot see variable "number" directly inside of action listener , have access instance of scenario in. can done scenario.this
Comments
Post a Comment