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

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -