JavaFX:如何触发TreeItem事件

时间:2016-11-15 12:40:54

标签: events javafx treetable

我将myClass extends TreeItem<file>作为TreeTableView中的数据模型,主要遵循此处的示例: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
      };
}

我添加了一个将子项添加到此项目的函数。我对TreeTableView的正确更新有疑问。更多细节见下面的代码和评论:

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?

}

如何正确抛出此事件?

1 个答案:

答案 0 :(得分:0)

似乎我对JavaFX中触发的工作方式存在误解。现在最简单的解决方案是:

@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;
}