简体   繁体   中英

How to add multiple children in a list into a pane in Java FX

I am trying to create multiple objects and then put those into my scene. For this I am using a loop to create new object in each iteration and insert that into the list.

//single object
robot = new Circle(25, Color.BLUE);
robot.relocate(getRandomCoordinates(600), getRandomCoordinates(400));

ArrayList<Circle> particles = new ArrayList<Circle>();

//multiple objects in list particles
for(int i = 0; i < 10; i++)
{
  particles.add(new Circle(10, Color.GREEN));
}

Now the main issue is how can I insert the list of objects into my pane. For a single object I am using this:

playground.getChildren().addAll(robot);

How can I add the list of objects into my Pane - playground ?

Thanks!

When you are only adding a single node, you should prefer the add(...) method over the addAll(...) method:

playground.getChildren().add(robot);

ObservableList<Node> inherits the addAll(Collection<Node>) method from List<Node> . So you can just do

playground.getChildren().addAll(particles);

Note there is a second method called addAll(...) which is a varargs method, taking a list of Node parameters. This is specific to ObservableList (not just to List ).

Of course, you can also just add each element one at a time:

for (Node node : particles) {
    playground.getChildren().add(node);
}

or, if you prefer a Java 8 approach:

particles.forEach(playground.getChildren()::add);

The difference between this approach and using addAll(particles) is that listeners registered with the children list will be notified only once for addAll(...) , but will be notified once for each element if you add each element one at a time. So there will potentially be a performance enhancement using addAll(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM