Running JavaFX on scenography controls

How can I iterate over scene controls? I tried with getChildrenUnmodifiable (), but it only returns 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()); } } } 
+7
source share
2 answers

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); } } } 
+8
source

Here's the modified version of amru answer I'm using, this method gives you components of a certain 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 the components:

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

To get only buttons:

 List<Button> buttons= getNodesOfType(pane, Button.class); 
+3
source

All Articles