Chris
Chris

Reputation: 2465

JavaFx - When are elements created

I am attempting to access elements of an Accordian prior to actually viewing the screen but every time I access it, it has no children. Once I have visited the stage, the children appear. I have built this scene in SceneBuilder and it works as expected once all the components are visible on the screen.

The entire structure is loaded using FXMLLoader. I can't post the code due to the size of the project (30k + lines of code). I have verified that the FXMLLoader is running and I get all the top-level elements in the Parent specified. (Works as intended up until I try to access the elements before loading the stage)

I have tried to call start(stage) on all the different stages in the application in an effort to force them to load fully but I still got the same results.

Here is the code for getting all the children of a Node which works fine after the stage has been visible on the screen, until then only top-level items are found and they all have 0 children.

public static ObservableList<Node> getAllChildren(Node n) {
        ObservableList<Node> allChildren = FXCollections.observableArrayList();

        ObservableList<Node> children = ((Parent) n).getChildrenUnmodifiable();

        for (Node c : children) {
            if (c instanceof Parent) {
                ObservableList<Node> cp = ((Parent) c).getChildrenUnmodifiable();
                if (cp.size() > 0) { // 0 for all top-level Parents until the stage has been visually loaded.
                    ObservableList<Node> nodes = getAllChildren(c);
                    for (Node node : nodes) {
                        allChildren.add(node);
                    }
                }
            }

            allChildren.add(c);
        }

        return allChildren;
    }

EDIT: Further testign reveals that the structure is in fact built on elements (in this case a TabPane, I am able to use getTabs().get(n).getContent() and will get the tabs WITH their children as expected. However, at this time in the execution, I still get that the TabPane has no children. It does not have children until after the stage has been displayed.

Upvotes: 1

Views: 45

Answers (1)

fabian
fabian

Reputation: 82461

A Controls children are added to the Contol when the skin is created, which by default happens when the Control is layouted for the first time.

TitledPane tp = new TitledPane();

Accordion acc = new Accordion(tp);
System.out.println(acc.getChildrenUnmodifiable().size()); // 0

Scene scene = new Scene(acc);

// layout happens here
acc.applyCss();
acc.layout();

System.out.println(acc.getChildrenUnmodifiable().size()); // 1

Upvotes: 2

Related Questions