pdeva
pdeva

Reputation: 45571

How to display root element in JFace TreeViewer?

I have a JFace Treeviewer, however it does not display the 'root' element that is passed as input. Only the children of the root are shown. Is it possible to display the root too?

Upvotes: 3

Views: 4333

Answers (3)

Harry Siebert
Harry Siebert

Reputation: 11

The TreeViewer's input element should not be displayed. The problem can be solved like this:

treeViewer.setInput("root");

And in the ContentProvider:

public Object[] getElements(Object arg0) {
    return new Object[] { rootItem }; // your root item you want to display
}

Upvotes: 1

Sytse Goedemoed
Sytse Goedemoed

Reputation: 9

I ran into exactly the same problem and solved it by using a boolean field treeInputSet as follows in which Model is the domain class you want to display in the tree:

// Field to hold whether tree input was set
private boolean treeInputSet = false;    

// Other code...    

@Override 
public Object[] getElements(Object inputElement)
{
    if (inputElement instanceof Model)
    {
        if (treeInputSet)
        {
            Model model = (Model) inputElement;
            return model.getChildren().values().toArray();
        }
        else
        {
            treeInputSet = true;
            return new Object[] { inputElement };
        }
    }
    return null;
}

Upvotes: -1

Prakash G. R.
Prakash G. R.

Reputation: 4892

The input is not decided as the root of the TreeViewer. Infact the treeviewer doesn't know which one is root and which one is not. Its decided by the contentprovider.getElements() methods. With most probability, I guess you are calling the getChildren() inside that method. That leads to returning the children of the root elements rather than returning the root elements themselves.

Upvotes: 3

Related Questions