2016-11-15 4 views
0

У меня есть класс myClass extends TreeItem<file>, который будет использоваться как датамодель в TreeTableView, в основном следуя примеру здесь: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TreeItem.html.JavaFX: Как инициировать событие 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» с помощью соответствующего конструктора, а затем предоставите «TreeItem» в качестве цели в Event.fire (...) '. –

ответ

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; 
} 
Смежные вопросы