如何将列表中的多个子项添加到 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);
如何将对象列表添加到我的窗格 - playground 中?
谢谢!
当您只添加一个节点时,您应该更喜欢 add(...)
方法而不是 addAll(...)
方法:
playground.getChildren().add(robot);
ObservableList<Node>
继承了 List<Node>
的 addAll(Collection<Node>)
方法。所以你可以做
playground.getChildren().addAll(particles);
请注意,还有第二种方法称为 addAll(...)
,它是一个可变参数方法,采用 Node
参数列表。这是 ObservableList
特有的(不仅仅是 List
)。
当然,你也可以一次只添加一个元素:
for (Node node : particles) {
playground.getChildren().add(node);
}
或者,如果您更喜欢 Java 8 方法:
particles.forEach(playground.getChildren()::add);
此方法与使用 addAll(particles)
的区别在于,在子列表中注册的侦听器只会在 addAll(...)
时收到一次通知,但如果添加每个元素,每个元素都会收到一次通知一次一个。因此,使用 addAll(...)
.
可能会提高性能
我正在尝试创建多个对象,然后将它们放入我的场景中。为此,我使用循环在每次迭代中创建新对象并将其插入到列表中。
//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);
如何将对象列表添加到我的窗格 - playground 中?
谢谢!
当您只添加一个节点时,您应该更喜欢 add(...)
方法而不是 addAll(...)
方法:
playground.getChildren().add(robot);
ObservableList<Node>
继承了 List<Node>
的 addAll(Collection<Node>)
方法。所以你可以做
playground.getChildren().addAll(particles);
请注意,还有第二种方法称为 addAll(...)
,它是一个可变参数方法,采用 Node
参数列表。这是 ObservableList
特有的(不仅仅是 List
)。
当然,你也可以一次只添加一个元素:
for (Node node : particles) {
playground.getChildren().add(node);
}
或者,如果您更喜欢 Java 8 方法:
particles.forEach(playground.getChildren()::add);
此方法与使用 addAll(particles)
的区别在于,在子列表中注册的侦听器只会在 addAll(...)
时收到一次通知,但如果添加每个元素,每个元素都会收到一次通知一次一个。因此,使用 addAll(...)
.