eclipsejfacercptreeviewer

Updating Eclipse JFace Treeviewer when model changes?


I am developing a RCP application with a TreeViewer. While there are good number of articles to explain how to add editing support to the Viewer (and how changes in view are updated in the model), I don't find much for updating the Treeview when the underlaying model changes. my question in short:

TreeView ----> Model updation ------ there are lots of examples

Model ----> Treeview updation ----- this is my question

Edit: This is what I tried and it works. comments please

viewer.getTree().addKeyListener(new KeyListener(){

    @Override
    public void keyPressed(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

        if(e.keyCode==SWT.F3){
            System.out.println("F3 pressed... new element will be added");
            TreeParent root = (TreeParent) viewer.getInput();
            TreeParent activityRoot = (TreeParent) root.getChildren()[0];
            activityRoot.addChild(new TreeObject("NEW_ACTIVITY"));
            //viewer.update(root, null);
            viewer.refresh();
        }

    }

    });

Solution

  • The data model is provided by your content provider, TreeViewer does not provide any means of changing this data - you must do that it your own code. When you have changed to model you can use the following methods to tell the TreeViewer about the change:

    If you have just changed what needs to be shown for a single item in the tree use

    TreeViewer.update(object, null);
    

    to get that item in the tree updated. There is also an array version of this to update multiple objects.

    If you have added or removed objects in the tree use

    TreeViewer.refresh();
    

    to rebuild the whole tree or

    TreeViewer.refresh(object);
    

    to refresh the part of the tree start at object.

    To tell the tree about adding and removing objects there are

    TreeViewer.add(parent, object);
    TreeViewer.remove(object);
    

    there are also array variants of these.

    To help the TreeViewer find the objects call

    TreeViewer.setUseHashlookup(true);
    

    (must be called before TreeViewer.setInput). Since this uses a hash table the objects should have sensible hashCode and equals methods. You can also use TreeViewer.setComparer to specify a different class to do the hash code and comparison.