Alex Rivera | Logout

access to variable within inner class in java

Asked 2010-10-10T18:30:21.990
17

I'm trying to create an array of JLabels, all of them should go invisible when clicked. The problem comes when trying to set up the mouse listener through an inner class that needs access to the iteration variable of the loop used to declare the labels. Code is self-explanatory:

    for(int i=1; i<label.length; i++) {
       label[i] = new JLabel("label " + i);
       label[i].addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent me) {
             label[i].setVisible(false);   // compilation error here
          }
       });
       cpane.add(label[i]);
    }

I thought that I could overcome this by the use of this or maybe super instead of the call of label[i] within the inner method but I haven't been able to figure it out.

The compilation error is: local variable i is accessed from within inner class; needs to be declared final`

I'm sure that the answer must be something really silly I haven't thought of or maybe I'm making some small mistake.

Any help would be appreciated

Edit
Report

1 Answer

4

If you're having a problem accessing i, make another variable outside the scope of your inner-class (e.g. before label[i].addMouseListener(...)):

for(int i=1; i<label.length; i++) {
   label[i] = new JLabel("label " + i);

   final int localI = i;
   label[i].addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent me) {
         label[localI].setVisible(false);
      }
   });
   cpane.add(label[i]);
}
answered 2010-10-10T18:36:49.913

Your Answer