0

I am trying to learn TreeViewer in RCP. I wrote this small piece of code for that.

public class TreeViewClass extends ViewPart {

public static final String ID = "TreeViewerDemo.treeView";

public TreeViewClass() {
    // TODO Auto-generated constructor stub
}

@Override
public void createPartControl(Composite parent) {

    TreeViewer treeViewer = new TreeViewer(parent, SWT.BORDER);
    Tree tree = treeViewer.getTree();

    TreeItem root = new TreeItem(tree, 0);
    root.setText("Root Node");

    TreeItem childNode1 = new TreeItem(root, 0);
    childNode1.setText("Child Node 1");

    TreeItem childNode2 = new TreeItem(childNode1, 0);
    childNode2.setText("Child Node 2");
}

@Override
public void setFocus() {
    // TODO Auto-generated method stub

}

}

When I am running this code, The tree gets displayed, but only the root node. When I click on the root node(with a arrow icon, which means it has children), the node does not display the children nodes. Later I discovered that, when I apply setExpanded(true) to a node, it gets displayed, otherwise, it doesn't.

Where is the problem in my code?

Thanks!

Srijani Ghosh
  • 3,935
  • 7
  • 37
  • 68
  • 1
    If you are using `TreeViewer` you should not use `TreeItem`. Instead you use a content provider and label provider. If you want to use `TreeItem` use `Tree`. Mixing the two will give unpredictable results. – greg-449 Sep 15 '15 at 09:01
  • Thanks a lot greg! Can you please provide an example using tree and Treeitem. I made a mess while trying to do so. So I was trying to use treeviewer. I would be grateful! Thanksa again! – Srijani Ghosh Sep 15 '15 at 09:02
  • 1
    I think just doing `new Tree` instead of TreeViewer is the only change. If you want nodes to be expanded you have to call `setExpanded`. – greg-449 Sep 15 '15 at 09:07
  • Thanks a lot... I am now able to do it...Did just as you said!.. Thanks a lot! – Srijani Ghosh Sep 15 '15 at 09:09

1 Answers1

1

If you are using TreeViewer you should not use TreeItem. Instead you use a content provider and label provider. If you want to use TreeItem use Tree. Mixing the two will give unpredictable results.

When using TreeItem you need to call setExpanded(true) on each item you want to be expanded.

greg-449
  • 109,219
  • 232
  • 102
  • 145