![](/img/trans.png)
[英]Pane will not add all children unless I individually add text first in JAVA / Java FX
[英]How to add multiple children in a list into a pane in Java FX
我试图创建多个对象,然后将其放入场景中。 为此,我使用循环在每次迭代中创建新对象并将其插入列表。
//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));
}
现在的主要问题是如何将对象列表插入到窗格中。 对于单个对象,我正在使用:
playground.getChildren().addAll(robot);
如何将对象列表添加到Pane-操场?
谢谢!
当您仅添加单个节点时,应addAll(...)
使用add(...)
方法而不是addAll(...)
方法:
playground.getChildren().add(robot);
ObservableList<Node>
从List<Node>
继承addAll(Collection<Node>)
方法。 所以你可以做
playground.getChildren().addAll(particles);
请注意,还有一个名为addAll(...)
的第二种方法,它是一个varargs方法,带有Node
参数列表。 这特定于ObservableList
(而不仅仅是List
)。
当然,您也可以一次添加一个元素:
for (Node node : particles) {
playground.getChildren().add(node);
}
或者,如果您更喜欢Java 8方法:
particles.forEach(playground.getChildren()::add);
这种方法与使用addAll(particles)
的区别在于,向子项列表注册的侦听器将仅对addAll(...)
进行一次通知,但如果您一次添加每个元素,则对每个元素仅进行一次通知。 因此,使用addAll(...)
可能会提高性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.