Java Swing Access Class Variables From Button -


so in java swing application, need button actionlistener able access variables outside of scope so:

int x = 13;  jbutton btn = new jbutton("new button"); btn.addactionlistener(new actionlistener() {     public void actionperformed(actionevent e) {         system.out.println(x);     } }); 

but variable out of scope error. how can access it?

the action listener anonymous inner class. means can use final variables outer scope. so, either declare x final or pass class other way.

this should work:

final int x = 13;  jbutton btn = new jbutton("new button");     btn.addactionlistener(new actionlistener() {     public void actionperformed(actionevent e) {         system.out.println(x);     } }); 

alternatively, see pass variables actionlistener in java other options.


Comments

Popular posts from this blog

xslt - Substring before throwing error -

Google Cloud Bigtable Durability/Availability Guarantees -

Android M doze mode and "native" posix socket freezing up -