我想用一个 for 循环创建一组十个不同的圆圈,当鼠标光标悬停在其中一个上时,每个圆圈都会改变颜色,并通过鼠标单击将它们更改为第三种颜色。然而,只有一个圆圈 - 最后一个在循环中创建的圆圈 - 具有颜色变化,无论哪个圆圈被点击或悬停。谁能解释我为什么以及如何解决这个问题?我会非常感激的。Hier 是我的代码:
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);
......