Search code examples
javaswttreeviewer

TreeViewer Expand-/Collapse-ToLevel Bug


I have a TreeViewer whose items I am trying to expand or collapse one level. My TreeViewer contains items that have the same name. For example:

Node 1
  -> Node A
      -> Node B
         -> Node C
Node 2
  -> Node A
      -> Node B
         -> Node C

Even if I select the second Node A to expand or collapse, it will still expand or collapse the first Node A.

My code for expand is:

ITreeSelection selection = (ITreeSelection) tree.getSelection();
TreeNode selectedItem = (TreeNode) selection.getFirstElement();
tree.expandToLevel(selectedItem, 1);

My Code for collapse is:

ITreeSelection selection = (ITreeSelection) tree.getSelection();
TreeNode selectedItem = (TreeNode) selection.getFirstElement();
TreeNode[] children = selectedItem.getChildren();
if (children != null) {
    for (TreeNode child : children) {
         tree.collapseToLevel(child, 1);
    }
}

What can I do so that the TreeViewer expands and collapses the right selected item?


Solution

  • You must make sure that the equals method for different objects with the same name in the tree does not return true. The tree viewer will not be able to locate the correct tree items if equals returns true for two different objects. As always you must make hashCode compatible with the equals implementation.

    If you can't fix the equals method in the objects you can use IElementComparer to create a special compare for the tree viewer. Use TreeViewer.setComparer to set the comparer for the tree.