动态地将圆圈添加到 Arraylist

dynamically adding circles to an Arraylist

我在发帖前查找了类似的问题,但这些解决方案无助于回答我的问题。

我已经使用数组解决了这个问题,但使用 ArrayList 会更好。我创建了一个事件来检查左键单击以创建一个圆对象并将其添加到列表中。问题是,当我使用这段代码时,arrayList 中没有添加圆圈,也没有给出编译错误。如何从 ArrayList 向窗格添加圆圈?

    public class test extends Application {
         static int index = 0;
         @Override
         public void start(Stage primaryStage) throws Exception {
         Pane = pane = new Pane();
         ArrayList<Circle> circles = new ArrayList<Circle>();

         pane.setOnMouseClicked( e -> {

            if (e.getButton() == MouseButton.PRIMARY) {

              circles.add(new Circle(e.getX(), e.getY(), 5));
              circles.get(index).setStroke(Color.BLACK);
              circles.get(index).setFill(Color.WHITE);
              index++;

            }
         });

         pane.getChildren().addAll(circles);

         Scene scene = new Scene(pane, 400, 400);
         primaryStage.setScene(scene);
         primaryStage.show();
    }

    public static void main(String[] args) {
         launch(args);
    }

}

只需在创建时将圆添加到窗格以及数组列表即可:

pane.setOnMouseClicked( e -> {

    if (e.getButton() == MouseButton.PRIMARY) {

       Circle circle = new Circle(e.getX(), e.getY(), 5) ;
       circles.add(circle);
       pane.getChildren().add(circle);
       circle.setStroke(Color.BLACK);
       circle.setFill(Color.WHITE);

       // not sure what index is for. Looks like it would always be
       // equal to circles.size()
       index++;

    }
});