import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;

public class TreeDemo {

	public static Display myDisplay;
	public static boolean internalCall = false;

	public static void main(String[] args) {
		internalCall = true;
		myDisplay = new Display();
		TreeDemo td = new TreeDemo();
		td.runDemo(myDisplay);
	}
	
	public void runDemo(Display display) {
		myDisplay = display;
		Shell shell = new Shell(display);
		shell.setText("Tree Demo");

		shell.setSize(300,300);
		shell.open();

		//create the tree, give it a border, set its size/location
		//SWT.MULTI indicates multiple items in the tree can be
		//selected at once.  SWT.SINGLE restricts it to just one
		final Tree tree = new Tree(shell, SWT.MULTI | SWT.BORDER);
		tree.setSize(150, 150);
		tree.setLocation(5,5);
	
		//create 3 nodes at the same, highest level
		//note the third uses a 3rd argument to its
		//constructor to say what index it should have in
		//the tree(1).  Otherwise they would simply
		//appear in the order they were created here
		TreeItem myComp = new TreeItem(tree, SWT.NONE);
		myComp.setText("My Computer");
		TreeItem netPlaces = new TreeItem(tree, SWT.NONE);
		netPlaces.setText("My Network Places");
		TreeItem myDocs = new TreeItem(tree, SWT.NONE, 1);
		myDocs.setText("My Documents");

		//create 2 nodes under My Computer, 2nd level
		//the 2nd one passes 0 to become the sub-node at index
		//0 in the list
		TreeItem hardDisk = new TreeItem(myComp, SWT.NONE);
		hardDisk.setText("Local Disk (C:)");
		TreeItem floppy = new TreeItem(myComp, SWT.NONE, 0);
		floppy.setText("3.5 Floppy (A:)");
		
		//create an item 2 levels down, under Local Disk
		TreeItem progFiles = new TreeItem(hardDisk, SWT.NONE);
		progFiles.setText("Program Files");

		//load an arrow image
		Image icon = new Image(display, "EclipseBannerPic.jpg");
		//add an image to the program files treeitem.
		progFiles.setImage(icon);
		
		//add a listener for changes to the selection(s)
		//in the tree
		tree.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				TreeItem[] t = tree.getSelection();
				System.out.print("Selection: ");
				for(int i = 0; i < t.length; i++) {
					System.out.print(t[i].getText() + ", ");
				}
				System.out.println();
			}
		});
		
		//listen for expansion and collapse of the tree
		//and print a message to the console
		tree.addTreeListener(new TreeListener() {
			public void treeCollapsed(TreeEvent e) {
				System.out.println("Tree collapsed.");	
			}
			public void treeExpanded(TreeEvent e) {
				System.out.println("Tree expanded.");
			}
		});
		
		while(!shell.isDisposed())
			if(!display.readAndDispatch())
				display.sleep();

		icon.dispose();
		if (internalCall) display.dispose();

	}

}
