setAutoExpandLevel不适用于TreeViewer

时间:2013-11-14 07:31:21

标签: java swt

我创建了TreeViewer,并为树{/ p>添加了setAutoExapandLevel

treeViewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
treeViewer.setContentProvider(new TreeContentProvider());
treeViewer.setLabelProvider(new TreeLabelProvider());
treeViewer.setAutoExpandLevel(3);
treeViewer.setInput(new Model());

树不能自动展开的问题

你知道它为什么不起作用吗?

1 个答案:

答案 0 :(得分:1)

在调用setInput()时,您确定模型包含所有数据吗?

internalExpandToLevel(Widget widget, int level)上调用

inputChanged(Object input, Object oldInput)(进行扩展的地方)。如果在调用setInput时模型为空,则不会展开任何节点。即使您以后添加节点并调用刷新。

为了证明这一点,我从another question的答案中更改了我的代码段。

按原样运行此代码,然后将empty字段初始化为true运行。你会看到差异。

static boolean empty = false;

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    TreeViewer treeViewer = new TreeViewer(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
    treeViewer.setContentProvider(new DummyContentProvider());
    treeViewer.setAutoExpandLevel(3);
    treeViewer.setInput("root");

    empty = true;
    treeViewer.refresh();

    shell.setSize(200, 200);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

private static class DummyContentProvider implements ITreeContentProvider {

    @Override
    public Object[] getElements(Object inputElement) {
        return this.getChildren(inputElement);
    }

    @Override
    public Object[] getChildren(Object parentElement) {
        if (!empty) {
            return new Object[0];
        }
        switch ((String) parentElement) {
            case "root":
                return new String[]{"a", "b"};
            case "a":
                return new String[]{"1"};
            case "b":
                return new Object[]{"1", "2"};
            case "1":
                return new Object[]{"x", "y"};
            default:
                return new String[0];
        }
    }

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

    @Override
    public boolean hasChildren(Object element) {
        return this.getChildren(element).length > 0;
    }

    @Override
    public void dispose() {
    }

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