1

All this rectangles are added in grid and I want after click each of them to change the color to white, but program throwing and exception.

Can i do this with this way or I need to get the position of rectangle a make on his place a new one ?

Rectangle[] rec = new Rectangle[22 * 12];
    for( int i = 0; i < 22 * 12; i++){
        rec[i] = new Rectangle(32, 32);
        rec[i].setStroke(Color.BLACK);
        rec[i].setFill( Color.valueOf("#202020") );
        rec[i].setStrokeWidth(1);
        rec[i].setOnMouseClicked(e -> {
            Rectangle r = new Rectangle(32, 32, Color.WHITE);
            rec[i].setFill( Color.WHITE); // exception at this line -> i must be final or ...
        });

}
1
  • That's a compile error, not an exception. Commented Jan 4, 2016 at 18:46

1 Answer 1

1

As your compile error says, you can't access non-final variables in a lambda expression. You can get around this by putting your rectangle in a different (effectively-final) variable:

Rectangle[] rec = new Rectangle[22 * 12];
    for( int i = 0; i < 22 * 12; i++){
        Rectangle r = new Rectangle(32, 32);
        r.setStroke(Color.BLACK);
        r.setFill( Color.valueOf("#202020") );
        r.setStrokeWidth(1);
        r.setOnMouseClicked(e -> {
            r.setFill( Color.WHITE); 
        });

        rec[i] = r ;
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.