[英]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 ? 如何将对象列表添加到Pane-操场?
Thanks! 谢谢!
When you are only adding a single node, you should prefer the add(...)
method over the addAll(...)
method: 当您仅添加单个节点时,应addAll(...)
使用add(...)
方法而不是addAll(...)
方法:
playground.getChildren().add(robot);
ObservableList<Node>
inherits the addAll(Collection<Node>)
method from List<Node>
. ObservableList<Node>
从List<Node>
继承addAll(Collection<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. 请注意,还有一个名为addAll(...)
的第二种方法,它是一个varargs方法,带有Node
参数列表。 This is specific to ObservableList
(not just to List
). 这特定于ObservableList
(而不仅仅是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: 或者,如果您更喜欢Java 8方法:
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. 这种方法与使用addAll(particles)
的区别在于,向子项列表注册的侦听器将仅对addAll(...)
进行一次通知,但如果您一次添加每个元素,则对每个元素仅进行一次通知。 So there will potentially be a performance enhancement using addAll(...)
. 因此,使用addAll(...)
可能会提高性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.