create Recursive Child Observer for JavaFX - Java JavaFX

Java examples for JavaFX:Node

Description

create Recursive Child Observer for JavaFX

Demo Code


//package com.java2s;

import javafx.collections.ListChangeListener;
import javafx.scene.Node;
import javafx.scene.Parent;

import java.util.function.Consumer;

public class Main {
    private static ListChangeListener<Node> createRecursiveChildObserver(
            Consumer<Node> onRemove, Consumer<Node> onAdd) {
        return new ListChangeListener<Node>() {
            @Override/*ww  w.j ava  2s  .  c  o  m*/
            public void onChanged(Change<? extends Node> change) {
                while (change.next()) {
                    if (change.wasAdded()) {
                        for (Node addedChild : change.getAddedSubList()) {
                            if (addedChild instanceof Parent) {
                                ((Parent) addedChild)
                                        .getChildrenUnmodifiable()
                                        .addListener(this);
                            }
                            onAdd.accept(addedChild);
                        }
                    }
                    if (change.wasRemoved()) {
                        for (Node removedChild : change.getRemoved()) {
                            if (removedChild instanceof Parent) {
                                ((Parent) removedChild)
                                        .getChildrenUnmodifiable()
                                        .removeListener(this);
                            }
                            onRemove.accept(removedChild);
                        }
                    }
                }
            }
        };
    }
}

Related Tutorials