Search code examples
javatreeviewjfacetreeviewer

java treeviewer add element


basically I am working with a treeviewer in Java (org.eclipse.jface.viewers.TreeViewer). Now my problem is, that I want to add an childelement/ item to an existing knot.

First of all my tree looks like this:

Knot A
Knot B
Knot C
 >child1
 >child2

These children(child1, child2) arent added manually, they are generated before I get my hands on the tree itself.

  1. I create the treeviewer: viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
  2. I populate the treeviewer: viewer.setInput(....elements()); which generates the state from above.

  3. viewer.getTree().getItem(0) returns the correct knot A of my tree.

But I cant add a new child to an existing knot. I tried the following and other things:

TreeItem newItem = new TreeItem(items[0], SWT.NONE); and viewer.add(items[0], newItem); with a newly created item viewer.refresh();

Theoretically I could manipulate the arrayList which populates the treeviewer in the first place but that would be really bad I think.

I really do not know what I am doing wrong right now. I guess it is a quite silly question. If that is the case, then I am sorry.^^

Thank you for your help, I am grateful for every hint that you can offer.


Solution

  • Updating your 'model' (the data you give to setInput) is the correct way to update the tree. Call TreeViewer.refresh() or TreeViewer.refresh(element) to get the tree viewer to update the tree from the model.

    When you are using TreeViewer you never create TreeItem objects - the viewer does that. Everything you pass to the refresh, update, add ... methods are objects from your model not TreeItems.