find JavaFX Child By ID - Java JavaFX

Java examples for JavaFX:Node

Description

find JavaFX Child By ID

Demo Code


import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Accordion;
import javafx.scene.control.Labeled;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TitledPane;
import javafx.scene.text.Font;
import javafx.stage.Popup;
import javafx.stage.PopupBuilder;

public class Main{
    @SuppressWarnings("unchecked")
    private static <T> T findChildByID(Parent parent, String id)
            throws WidgetNotFoundException {

        String nodeId;/*from w  w  w.j av a 2s.c om*/

        if (parent instanceof TitledPane) {
            TitledPane titledPane = (TitledPane) parent;
            Node content = titledPane.getContent();
            nodeId = content.idProperty().get();

            if (nodeId != null && nodeId.equals(id)) {
                return (T) content;
            }

            if (content instanceof Parent) {
                T child = findChildByID((Parent) content, id);
                if (child != null) {
                    return child;
                }
            }
        }

        for (Node node : parent.getChildrenUnmodifiable()) {
            nodeId = node.idProperty().get();
            if (nodeId != null && nodeId.equals(id)) {
                return (T) node;
            }

            if (node instanceof SplitPane) {
                SplitPane splitPane = (SplitPane) node;
                for (Node itemNode : splitPane.getItems()) {
                    nodeId = itemNode.idProperty().get();

                    if (nodeId != null && id.equals(id)) {
                        return (T) itemNode;
                    }

                    if (itemNode instanceof Parent) {
                        T child = findChildByID((Parent) itemNode, id);

                        if (child != null) {
                            return child;
                        }
                    }
                }
            } else if (node instanceof Accordion) {
                Accordion accordion = (Accordion) node;
                for (TitledPane titledPane : accordion.getPanes()) {
                    nodeId = titledPane.idProperty().get();

                    if (nodeId != null && nodeId.equals(id)) {
                        return (T) titledPane;
                    }

                    T child = findChildByID(titledPane, id);

                    if (child != null) {
                        return child;
                    }
                }
            } else if (node instanceof Parent) {
                T child = findChildByID((Parent) node, id);

                if (child != null) {
                    return child;
                }
            }
        }
        return null;
    }
}

Related Tutorials