0

TreeViewer我创造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());

树不是自动扩展的问题

你知道为什么它不工作吗?

4

1 回答 1

1

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

internalExpandToLevel(Widget widget, int level)(发生扩展的地方)被调用inputChanged(Object input, Object oldInput)。如果setInput调用时模型为空,则不会展开任何节点。即使您稍后添加节点并调用刷新。

为了证明这一点,我从另一个问题的答案中更改了我的片段。

按原样运行此代码,然后使用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) {
    }
}
于 2013-11-14T08:25:37.883 回答