0

Below is my code and the variable i in circles[0][i] is not accessible. Can someone explain why and how to solve this?

Button[] buttons=new Button[b.getRow()];
int i=0;
GridPane buttonsPane=new GridPane();
for(i=0;i<b.getRow();i++)
{   
    buttons[i]=new Button("Row"+(i+1));
    buttonsPane.addColumn(i+1, buttons[i]);
    buttons[i].setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent event) 
        {
            circles[0][i].text.setText("Clicked.");
        }
    });
}
Sarath Chandra
  • 1,850
  • 19
  • 40
vmc
  • 3
  • 4
  • Please share how the `circles` array is being used in addition to given code. How is `circles` array related to `buttons` array – Sarath Chandra Jul 24 '17 at 06:36
  • Not accessible means what? What is the exact exception you are seeing? If the problem is with `circle`, you need to give codes related to `circle`. – Jai Jul 24 '17 at 06:36
  • Hello Mate, To start with, I did not have any issues with the Circle object. nor the circles array its only a case where I wanted the variable i which was initiated in the second line is not accessible inside the button handler. It asks to have a final variable to be used instead of a dynamic value. It works perfectly when I use a static value instead of a variable. I hope this helps. – vmc Jul 24 '17 at 06:41

1 Answers1

2

You are trying to access a variable from an inner scope (a method-local-anonymous-inner-class) - it must be declared as final.

You can do this:

for(i=0;i<b.getRow();i++)
{   
    buttons[i]=new Button("Row"+(i+1));
    buttonsPane.addColumn(i+1, buttons[i]);
    final index = i;
    buttons[i].setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent event) 
        {
            circles[0][index].text.setText("Clicked.");
        }
    });
}
yakobom
  • 2,681
  • 1
  • 25
  • 33