Ambidextrous
Ambidextrous

Reputation: 872

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!

Upvotes: 1

Views: 9739

Answers (1)

James_D
James_D

Reputation: 209340

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(...).

Upvotes: 4

Related Questions