javaswtjfacetreeviewer

TreeViewer doesn't show input


I have a TreeViewer with a content and label provider. When I set the input, the data doesn't show up, I only have a blank view. What am I doing wrong?

In the code below I show how I create the TreeViwer and the providers. The parent should be strings and the children are the substrings (i.e. letters) of the parent.

How I create the TreeViwer:

    Tree tree = new Tree(top, SWT.CHECK | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);

    tree.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));

    TreeViewer treeViewer = new TreeViewer(tree, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);

    treeViewer.setContentProvider(new TestContentProvider());
    treeViewer.setLabelProvider(new TestLabelProvider());

    List<String> input = new ArrayList<String>();

    input.add("abc");
    input.add("test");
    treeViewer.setInput(input);

The providers:

public class TestLabelProvider extends LabelProvider {

    @Override
    public String getText(Object element) {
        if (element instanceof String) {
            return ((String) element);
        }
        return "none";
    }
}




public class TestContentProvider implements ITreeContentProvider {

    private static final Object[] EMPTY_ARRAY = new Object[0];

    @Override
    public Object[] getElements(Object inputElement) {
        if (inputElement instanceof List) {
            return ((List<String>) inputElement).toArray();
        } else {
            return EMPTY_ARRAY;
        }
    }

    @Override
    public boolean hasChildren(Object element) {
        if (element instanceof String) {
            return true;
        }
        return false;
    }

    @Override
    public Object[] getChildren(Object parentElement) {
        if (parentElement instanceof String) {
            String s = (String) parentElement;
            return s.split("");
        }
        return EMPTY_ARRAY;
    }

    @Override
    public void dispose() {
    }

    @Override
    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
    }

    @Override
    public Object getParent(Object element) {
        return null;
    }

}

Solution

  • You are using the wrong constructor for TreeViewer. If you already has a Tree you must use:

    TreeViewer treeViewer = new TreeViewer(tree);
    

    (no style flags).

    The constructor you are using is creating a second tree inside the first tree - which doesn't work.