我在 javaFX GUI 上遇到了这个问题...我想当我按下按钮时我验证是否没有空 Pane ,否则我添加一个新 Pane ..但每次我得到 ConcurrentModificationException 。我尝试过打印,我发现这里只执行了 for 的第一部分,而没有执行其他部分
enter code here
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
for (Node node : vbox.getChildren()) {
if (node instanceof Pane){
Pane pane = (Pane) node ;
if (pane.getChildren().isEmpty()){
vbox.getChildren().remove(node);
}
}``
}
drugrow drug = new drugrow();
vbox.getChildren().addAll(drug.getPane());
}
});
最佳答案
您在 foreach 循环中迭代 vbox 的子节点列表,同时从循环体的该列表中删除节点。然后迭代器通知列表状态已更改,因此抛出 ConcurrentModificationException因为它无法跟踪更改并保证迭代以有序的方式发生。这些类型的迭代器称为快速失败迭代器。
更好的方法是收集要删除的节点,并在完成列表迭代后将其删除。
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
final List<Node> removalCandidates = new ArrayList<>();
for (Node node : vbox.getChildren()) {
if (node instanceof Pane){
Pane pane = (Pane) node ;
if (pane.getChildren().isEmpty()){
removalCandidates.add(node);
}
}
}
vbox.getChildren().removeAll(removalCandidates);
drugrow drug = new drugrow();
vbox.getChildren().addAll(drug.getPane());
}
});
关于java - JavaFX 并发修改异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45223227/