I want to create a set of ten different circles with a for loop and have each of them change color when the mouse cursor hovers over one of them and also have them change to a third color with a mouse click. However only one of the circles - the last one to be created in the loop- has the color changes, regardless which circle gets clicked or hovered over. Can anyone explain me why and how can I fix this? I would be very greatful. Hier is is my code:
public class View extends Parent{
BorderPane gameScreen;
Group hexaBlock;
ArrayList<Circle> circleList = new ArrayList<>();
Circle circle;
...
public View(){
gameScreen = new BorderPane();
hexaBlock = new Group();
...
for(int y=0; y<2; y++ ){
for(double x=0; x<5; x++){
circle = new Circle(xPosition(hexagon width*x), yPosition(hexagon height*4*y), radius);
circleList.add(circle);
circle.setFill(Color.BLACK);
circle.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
circle.setFill(Color.CYAN);
}
});
circle.addEventHandler(MouseEvent.MOUSE_ENTERED, new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent t) {
circle.setFill(Color.RED);
}
});
circle.addEventHandler(MouseEvent.MOUSE_EXITED, new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent t) {
circle.setFill(Color.BLACK);
}
});
}
this.getChildren().add(gameScreen);
...
gameScreen.setCenter(hexaBlock);
...
hexaBlock.getChildren().addAll(circleList);
.....
circle
is a field. When the event handlers are run, the field's value is retrieved and in this case it contains the value last assigned to it, i.e. the circle created last.Note that you can access
final
(effectively final for java >= 8) local variables in surrounding scopes from anonymus classes. I recommend removing thecircle
field and declaringcircle
where you assign the value to it: