Search code examples
eventsjavafxtreetable

JavaFX: How to trigger TreeItem event


I have class myClass extends TreeItem<file> to be used as datamodel in a TreeTableView mostly following the example here: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TreeItem.html .

public class myTreeItem extends TreeItem<File> 
     private boolean isLeaf;
     private boolean isFirstTimeChildren = true;
     private boolean isFirstTimeLeaf = true;

     @Override public ObservableList<TreeItem<File>> getChildren() {
             // ... full code see link to Oracle documentation
      return super.getChildren();
      }

      private ObservableList<TreeItem<File>> buildChildren(TreeItem<File> TreeItem) {
             // ... full code see link to Oracle documentation
      };
}

I have added a function to add children to this item. I have problems with the correct update of the TreeTableView. More details see in the code and comments below:

public void addChild(String name) {
    itemManger.addChild(this.getValue(), name);  // Generate Child
    isFirstTimeChildren = true;       // Ensure that buildChildren() is called, when getchildren() is called. 

//  getChildren();                    // If I would activate this line, 
                                      // all listeners would be notified 
                                      // and the TreeTableView is updated. 
                                      // This is most likely due to the call super.getChildren();

   // However I want to throw the event on my own in order 
   // to avoid the extra call of  this.getChildren(). Here is my 
   // (not sufficent) try:
    EventType<TreeItem.TreeModificationEvent<MLDCostumizableItem>> eventType =  TreeItem.treeNotificationEvent();
    TreeModificationEvent<MLDCostumizableItem> event = new TreeModificationEvent<>(eventType,this);
    Event.fireEvent(this,  event);


    // Here I don't know how to get a value for target. 
    // Is there some standard target, which includes all FX components?

}

How the correctly throw this event?


Solution

  • Seems that I had a missunderstanding in how the triggering works in JavaFX. Now the most simple solution is:

    @Override  // Taken from Link
    public void update(Observable observ, Object arg1)  {
        if (observ!=this.item)
        {
            LOGGER.error(new MLDConnectionException("Unexpected call of update() with observ = " + observ.toString()));
            return;
        }
        // Build new Chidren list
        try {
            super.getChildren().removeIf((x) -> true);  // empty list
            super.getChildren().setAll(buildChildren(this));
        } catch (MLDConnectionException e) {
            LOGGER.error("Error when genereting children List: ", e);
        }
    
    }
    
    public File addChild(String name) throws MLDException {
    
        File newChild = itemManger.addChild(item, name);
        update(this.item, null);
        return newChild;
    }