java动态地将圆添加到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);
}
}
# 1 楼答案
创建圆时,只需将圆以及数组列表添加到窗格中即可: