Search code examples
javajavafxtreeviewjavafx-8observablelist

Synchronizing a TreeView with mulitple nested ObservableLists


I have an ObservableList of ObservableLists of ObservableLists...

It basically goes down 4 levels.

Goal has a list of

Objective has a list of

Strategy has a list of

Tactic has a list of

Task

Obviously, this looks like the perfect scenario for setting up a TreeView to display this data. How can do it so that any changes made in the structure will show up on the TreeView as well?

I'm thinking that the Goal will be the root node. Whenever an Objective is added to its list, we can listen for it and alert the goal that an Objective has just been created. How and where should I set up this listener though? Do I alert the Goal? Or do I alert some static utility class to update its TreeView?


Solution

  • Using ObservableList and adding Listeners, you could easily do your thing.

    Suppose you put a Listener on your Goal. Then you would watch some changes of Objective. If a change happen (for example a Objective added), you would target the TreeItem used the specific goal (with a Map for example), and then add a child to it.

    Of course you can simplify your job by having some methods like that:

    private void addObjective(TreeItem<Object> specificGoal, List<Strategy > objective){
        TreeItem<Object> objectiveTreeItem = new TreeItem<>(objective);
    
        for(List<Tactic> strategy: objective){
            addStrategy(objectiveTreeItem, strategy);
        }
        specificGoal.getChildren().add(objectiveTreeItem);
    }
    

    Having a method for each of your layers.

    Of course, if the amount of data is small, you could just wipe your TreeView items, and re-launch the method you used to create it with the updated List. Simpler but not optimized.