JavaFX:如何触发TreeItem事件

问题描述:

我有myClass extends TreeItem<file>类作为TreeTableView中的数据模型,主要遵循这里的示例:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TreeItem.htmlJavaFX:如何触发TreeItem事件

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? 

} 

如何正确地抛出这个事件?

+0

无论您immeditely刷新列表或触发导致列表被刷新应该有相同的效果,前一种方法的性能会更好的活动,所以为什么不叫'getChildren()'导致刷新?如果你不想要不必要的刷新,只要检查一下,如果所有的祖先都展开了...... – fabian

+0

我也希望对FX触发器有更深入的了解。因此我的问题。 – BerndGit

+1

我真的不明白你想在这里做什么,但通常我认为你会使用适当的构造函数创建一个'TreeItem.TreeModificationEvent',然后在'Event.fire()中提供一个'TreeItem'作为目标。 ...)'。 –

似乎我对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; 
}