Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX looping over scenegraph controls

How can I loop over the controls of the scene ? I tried with getChildrenUnmodifiable() but it returns only the first level of children.

public void rec(Node node){

    f(node);

    if (node instanceof Parent) {
        Iterator<Node> i = ((Parent) node).getChildrenUnmodifiable().iterator();

        while (i.hasNext()){
            this.rec(i.next());
        }
    }
}
like image 306
nailujed Avatar asked Oct 22 '12 12:10

nailujed


2 Answers

Here's a modified version of amru's answer that I am using, this method gives you the components of a specific type:

private <T> List<T> getNodesOfType(Pane parent, Class<T> type) {
    List<T> elements = new ArrayList<>();
    for (Node node : parent.getChildren()) {
        if (node instanceof Pane) {
            elements.addAll(getNodesOfType((Pane) node, type));
        } else if (type.isAssignableFrom(node.getClass())) {
            //noinspection unchecked
            elements.add((T) node);
        }
    }
    return Collections.unmodifiableList(elements);
}

To get all components:

List<Node> nodes = getNodesOfType(pane, Node.class);

To only get buttons:

List<Button> buttons= getNodesOfType(pane, Button.class);
like image 104
Utku Özdemir Avatar answered Sep 25 '22 21:09

Utku Özdemir


You need to scan recursively. For example:

private void scanInputControls(Pane parent) {
    for (Node component : parent.getChildren()) {
        if (component instanceof Pane) {
            //if the component is a container, scan its children
            scanInputControls((Pane) component);
        } else if (component instanceof IInputControl) {
            //if the component is an instance of IInputControl, add to list
            lstInputControl.add((IInputControl) component);
        }
    }
}
like image 36
amru Avatar answered Sep 24 '22 21:09

amru