java - Use non-local variables in actionlistener -


i want use variable in action listener of . code :

public class face {  public face(){      btn1 =  new jtogglebutton();     btn2 =  new jtogglebutton();     btn3 =  new jtogglebutton();     btn4 =  new jtogglebutton();     btn5 =  new jtogglebutton();     btn6 =  new jtogglebutton();  }   public start6(){      jtogglebutton[] btn = new javax.swing.jtogglebutton[5]; // array saving address of buttons      btn[0] = btn1 ;     btn[1] = btn2 ;     btn[2] = btn3 ;     btn[3] = btn4 ;     btn[4] = btn5 ;     btn[5] = btn6 ;     (int = 0 ; < 36 ; i++) {         btn[i].addactionlistener(new actionlistener() {              @override         public void actionperformed(actionevent e) {         btn[i].setsize(150, 150);         imageicon btnimage = new imageicon(getclass().getresource("/gameimages/" + /* picture name*/ + ".jpg" ));         image img = btnimage.getimage();         btn[i].seticon( new imageicon(img.getscaledinstance(225,160 ,image.scale_fast)));         x6p.add(btn[i]);         }     });     }      }   public javax.swing.jtogglebutton btn1;   public javax.swing.jtogglebutton btn2;   public javax.swing.jtogglebutton btn3;   public javax.swing.jtogglebutton btn4;   public javax.swing.jtogglebutton btn5;   } 

when want use btn array in action listener of btn array (same arrays) error :

local variables referenced inner class must final or final want when button clicked show it's icon ...

the error means says: array variable btn not final, cannot accessed inner class. making final fix problem:

final jtogglebutton[] btn = new ... 

another solution moving array class:

public javax.swing.jtogglebutton btn1; public javax.swing.jtogglebutton btn2; public javax.swing.jtogglebutton btn3; public javax.swing.jtogglebutton btn4; public javax.swing.jtogglebutton btn5; private javax.swing.jtogglebutton[] btn = new javax.swing.jtogglebutton[] {     btn1, btn2, btn3, btn4, btn5 }; 

this same thing, , make code shorter.

i want when button clicked show icon

you don't need use array @ all: rather referencing btn[i], reference e.getsource(). set button has been clicked - need cast it:

javax.swing.jtogglebutton sender = (javax.swing.jtogglebutton)e.getsource(); 

create 1 action listener outside loop, , set on buttons. eliminate array altogether:

// same listener instance can handle buttons actionlistener actlistener = new actionlistener() {          @override     public void actionperformed(actionevent e) {         javax.swing.jtogglebutton senderbutton = (javax.swing.jtogglebutton)e.getsource();         ... // want senderbutton here     } }; // add same listener buttons (int = 0 ; < 36 ; i++) {     btn[i].addactionlistener(actlistener); } 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -