简体   繁体   中英

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?

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.

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;
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM