ka3ak
ka3ak

Reputation: 3191

UI which looks and behaves as a SWT Tree

Is it possible to create a UI which looks and behaves as a SWT Tree but whose roots aren't of type TreeItem but of type SWT Tree?

Example (expand/collapse):

Tree 1
    Child 1
    Child 2
Tree 2
    Child 1
    Child 2


>Tree 1
>Tree 2

Add a new "Child 3" to the "Tree 1":

Tree 1
    Child 1
    Child 2
    Child 3
Tree 2
    Child 1
    Child 2

Here is what I've tried:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

public class LayoutExperiments {
    public static void main(String[] args) {
        Display display = new Display();

        final Shell shell = new Shell(display);
        shell.setText("SWT Trees");
        shell.setLayout(new FillLayout());
        shell.setSize(400, 300);

        GridLayout gridLayout = new GridLayout(1, true);
        gridLayout.marginHeight = 0;
        gridLayout.verticalSpacing = 0;
        shell.setLayout(gridLayout);

        final Tree tree1 = new Tree(shell, SWT.SINGLE);
        createSomeNodes(tree1, "Tree 1");

        final Tree tree2 = new Tree(shell, SWT.SINGLE);
        createSomeNodes(tree2, "Tree 2");

        tree1.addListener(SWT.Expand, new Listener() {

            @Override
            public void handleEvent(Event event) {
                shell.layout();
            }
        });

        tree1.addListener(SWT.Collapse, new Listener() {

            @Override
            public void handleEvent(Event event) {
                shell.layout();
            }
        });

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

    private static void createSomeNodes(Tree tree, String rootName) {
        TreeItem root = new TreeItem(tree, SWT.NONE);
        root.setText(rootName);
        for (int i = 0; i < 10; i++) {
            TreeItem child = new TreeItem(root, SWT.NONE);
            child.setText("Child of " + rootName);
        }
    }
}

But unfortunately it doesn't work as I expect.

Upvotes: 0

Views: 136

Answers (1)

ka3ak
ka3ak

Reputation: 3191

I've found the solution here Fire event after expand/collapse tree

My problem was that the tree is not yet expanded when SWT.Expand listener is executed. So its size couldn't be calculated correctly.

Upvotes: 0

Related Questions