I am building a chess game application with javafx and I'm encountering a problem that I don't quite understand. I am trying to implement mouse click events for my chess pieces, but when I try to do so for each piece using a for loop I get the error "local variables referenced from a lambda expression must be final or effectively final". However when I create each mouse event independently there's no problem.
public static ChessPiece[] BlackPieces = {
new ChessPieceRook("BLACK"),
new ChessPieceKnight("BLACK"),
new ChessPieceBishop("BLACK"),
new ChessPieceQueen("BLACK"),
new ChessPieceKing("BLACK"),
new ChessPieceBishop("BLACK"),
new ChessPieceKnight("BLACK"),
new ChessPieceRook("BLACK")};
this works:
BlackPieces[0].setOnMouseClicked((MouseEvent event) -> {
if (turn % 2 == 0) {
setSelection(BlackPieces[0]);
setSelectionClip(PieceClips[0]);
}
});
but this doesn't:
for (int i = 0; i < 8; i++) {
BlackPieces[i].setOnMouseClicked((MouseEvent event) -> {
if (turn % 2 == 0) {
setSelection(BlackPieces[i]);
setSelectionClip(PieceClips[i]);
}
});
}
can anyone explain this to me?