Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Eclipse Projects » JFace » List folders and files with Tree/TreeView with JFace
List folders and files with Tree/TreeView with JFace [message #753816] Fri, 28 October 2011 19:11 Go to next message
Zé  arlos is currently offline Zé arlos
Messages: 15
Registered: October 2011
Junior Member
Hi,

Now I am developing a sample plugin for Eclipse, to show all directories and files from my computer, using JFace (Tree and TreeView).

I want something like this:

----------------------------------
| Element | Number of Childrens |
----------------------------------
| + usr | 5 |
| + bin | 4 |
| file | |
| + games | 2 |
----------------------------------

I create the plugin View witch ViewPart, the ContentProvider and the TreeLabelProvider.

public class ListFiles extends ViewPart {
    /** The ID of the view as specified by the extension. */
    public static final String ID = "sortnumbers.views.SortNumbers";

    /**
     * The constructor.
     */
    public ListFiles() { }

    /**
     * This is a callback that will allow us to create the viewer and initialize it
     */
    public void createPartControl(Composite parent) {
        Tree tree = new Tree(parent, SWT.MULTI);
        tree.setHeaderVisible(true);
        tree.setLinesVisible(true);

        TreeColumn column0 = new TreeColumn(tree, SWT.NONE);
        column0.setText("Element");
        column0.setWidth(300);
        TreeColumn column1 = new TreeColumn(tree, SWT.NONE);
        column1.setText("Number");
        column1.setWidth(300);

        TreeViewer treeviewer = new TreeViewer(tree);
        treeviewer.setContentProvider(new TreeContentProvider());
        treeviewer.setLabelProvider(new TreeLabelProvider());
        treeviewer.setInput(new FolderNode(new File("/")));
    }

    @Override
    public void setFocus() {
        // TODO
    }
}

public class TreeContentProvider implements ITreeContentProvider
{
    public Object[] getChildren(Object parentElement) {
        return ((ITreeNode)parentElement).getChildren().toArray();
    }

    public Object getParent(Object element) {
        return ((ITreeNode)element).getParent();
    }

    public boolean hasChildren(Object element) {
        return ((ITreeNode)element).hasChildren();
    }

    public Object[] getElements(Object inputElement) {
        return getChildren(inputElement);
    }

    public void dispose() {
    }

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

public class TreeLabelProvider extends LabelProvider
{
    public String getText(Object element) {
        return ((ITreeNode)element).getName();
    }
}


To search for all Files in my computer I create the interface ITreeNode, TreeNode, FolderNode and FileNode...

public interface ITreeNode
{
    public String getName();

    public List getChildren();

    public boolean hasChildren();

    public ITreeNode getParent();
}

public abstract class TreeNode implements ITreeNode
{
    protected ITreeNode fParent;
    protected List fChildren;

    public TreeNode(ITreeNode parent) {
        fParent = parent;
    }

    public boolean hasChildren() {
        return true;
    }

    public ITreeNode getParent() {
        return fParent;
    }

    public List getChildren() 
    {
        if( fChildren != null )
            return fChildren;

        fChildren = new ArrayList();
        createChildren(fChildren);

        return fChildren;
    }

    /* subclasses should override this method and add the child nodes */
    protected abstract void createChildren(List children);
}

public class FolderNode extends TreeNode
{
    private File fFolder; /* actual data object */

    public FolderNode(File folder) {
        this(null, folder);
    }

    public FolderNode(ITreeNode parent, File folder) {
        super(parent);
        fFolder = folder;
    }

    public String getName() {
        return "FOLDER: " + fFolder.getName();
    }

    @Override
    protected void createChildren(List children)
    {
        File[] childFiles = fFolder.listFiles();
        for(int i=0; i<childFiles.length; i++)
        {
            File childFile = childFiles[i];
            if( childFile.isDirectory() )
                children.add(new FolderNode(this, childFile));
            else
                children.add(new FileNode(this, childFile));
        }
    }
}

public class FileNode extends TreeNode
{
    private File fFile; /* actual data object */

    public FileNode(ITreeNode parent, File file)
    {
        super(parent);
        fFile = file;
    }

    public String getName() {
        return "FILE: " + fFile.getName();
    }

    protected void createChildren(List children) {
    }

    public boolean hasChildren() {
        return false;
    }
}


But the result was:

----------------------------------
| Element | Number of Childrens |
----------------------------------
| + usr | + usr |
| + bin | + bin |
| file | file |
| + games | + games |
----------------------------------

I cannot understand why TreeView fill all fields with the same string... What I need to change? Confused


Thanks in advance Smile
Re: List folders and files with Tree/TreeView with JFace [message #753845 is a reply to message #753816] Sat, 29 October 2011 06:42 Go to previous messageGo to next message
Zé  arlos is currently offline Zé arlos
Messages: 15
Registered: October 2011
Junior Member
Hi,

I need to change the class TreeLabelProvider to this:
public class TreeLabelProvider extends BaseLabelProvider implements ITableLabelProvider
{
	@Override
	public Image getColumnImage(Object element, int columnIndex) {
		return null;
	}

	@Override
	public String getColumnText(Object element, int columnIndex) {
		if (columnIndex == 0)
            return ((ITreeNode)element).getName();
        else
            return Integer.toString(((ITreeNode)element).getChildren().size());
	}
}


---8<---

And about sorting the TreeViewer?! Rolling Eyes Should I create a Class witch extended ViewerComparator or ViewerSorter? And how can I implement the method compare to sort elements in the TreeViewer?


--
Thanks in advance
Re: List folders and files with Tree/TreeView with JFace [message #754003 is a reply to message #753845] Mon, 31 October 2011 07:46 Go to previous message
Zé  arlos is currently offline Zé arlos
Messages: 15
Registered: October 2011
Junior Member
Ok, after a couple of hours, I found the solution for this topic...

A TreeViewer with a Tree witch list the files and dir of your PC, with two columns 'Element' and 'Number of Files in a dir'... You can sort the Tree cliking in a column...


ListFiles
public class ListFiles extends ViewPart
{
	/** The ID of the view as specified by the extension. */
	public static final String ID = "sortnumbers.views.ListFiles";

	protected static final int COLUMN_ELEMENT = 0;
	protected static final int COLUMN_NUMBER = 1;

	private TreeViewer treeviewer;
	private Tree tree;
	private TreeColumn column0;
	private TreeColumn column1;
	private TreeSorter sorter = new TreeSorter(this);

	/**
	 * The constructor.
	 */
	public ListFiles() { }

	/**
	 * This is a callback that will allow us to create the viewer and initialize it
	 */
	public void createPartControl(Composite parent)
	{
		tree = new Tree(parent, SWT.MULTI);
		tree.setHeaderVisible(true);
		tree.setLinesVisible(true);

		column0 = new TreeColumn(tree, SWT.NONE);
		column0.setText("Element");
		column0.setWidth(300);
		sorter.addColumn(column0, COLUMN_ELEMENT);

		column1 = new TreeColumn(tree, SWT.NONE);
		column1.setText("Number");
		column1.setWidth(300);
		sorter.addColumn(column1, COLUMN_NUMBER);

		TreeColumn sortColumn = null;
		switch (sorter.getSortColumn())
		{
			case COLUMN_ELEMENT:
				sortColumn = column0;
				break;
			case COLUMN_NUMBER:
				sortColumn = column1;
				break;
		}

		sorter.setSortColumnAndDirection(sortColumn, sorter.isReverseSort() ? SWT.DOWN : SWT.UP);

		treeviewer = new TreeViewer(tree);
		treeviewer.setComparator(sorter);
		treeviewer.setContentProvider(new TreeContentProvider());
		treeviewer.setLabelProvider(new TreeLabelProvider());
		treeviewer.setInput(new FolderNode(new File("/home/zecarlos/Documents/Teste/")));
	}

	protected void refreshViewer() {
		treeviewer.refresh();
	}

	@Override
	public void setFocus() {
		// empty
	}
}


ITreeNode
public interface ITreeNode
{
	public String getName();

	public List getChildren();

	public boolean hasChildren();

	public ITreeNode getParent();
}


TreeNode
public abstract class TreeNode implements ITreeNode
{
	protected ITreeNode fParent;
	protected List fChildren;
	protected String number;

	public TreeNode(ITreeNode parent) {
		fParent = parent;
	}

	public boolean hasChildren() {
		return true;
	}

	public ITreeNode getParent() {
		return fParent;
	}

	public List getChildren() 
	{
		if( fChildren != null )
			return fChildren;

		fChildren = new ArrayList();
		createChildren(fChildren);

		return fChildren;
	}

	/* subclasses should override this method and add the child nodes */
	protected abstract void createChildren(List children);
}


FolderNode
public class FolderNode extends TreeNode
{
	private File fFolder; /* actual data object */

	public FolderNode(File folder) {
		this(null, folder);
	}

	public FolderNode(ITreeNode parent, File folder) {
		super(parent);
		fFolder = folder;
	}

	public String getName() {
		return fFolder.getName();
	}

	@Override
	protected void createChildren(List children)
	{
		File[] childFiles = fFolder.listFiles();

		for(int i=0; i<childFiles.length; i++)
		{
			File childFile = childFiles[i];
			if( childFile.isDirectory() )
				children.add(new FolderNode(this, childFile));
			else
				children.add(new FileNode(this, childFile.getName()));
		}
	}
}


FileNode
public class FileNode extends TreeNode
{
	private String name; /* actual data object */

	public FileNode(ITreeNode parent, String name) {
		super(parent);
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	protected void createChildren(List children) {
		// empty
	}

	public boolean hasChildren() {
		return false;
	}
}


TreeContentProvider
public class TreeContentProvider implements ITreeContentProvider
{
	public Object[] getChildren(Object parentElement) {
		return ((ITreeNode)parentElement).getChildren().toArray();
	}
 
	public Object getParent(Object element) {
		return ((ITreeNode)element).getParent();
	}
 
	public boolean hasChildren(Object element) {
		return ((ITreeNode)element).hasChildren();
	}
 
	public Object[] getElements(Object inputElement) {
		return getChildren(inputElement);
	}
 
	public void dispose() {
	}
 
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
	}
}


TreeLabelProvider
public class TreeLabelProvider extends BaseLabelProvider implements ITableLabelProvider
{
	@Override
	public Image getColumnImage(Object element, int columnIndex) {
		return null;
	}

	@Override
	public String getColumnText(Object element, int columnIndex) {
		if (columnIndex == 0)
            return ((ITreeNode)element).getName();
        else
            return Integer.toString(((ITreeNode)element).getChildren().size());
	}
}


TreeSorter
public class TreeSorter extends ViewerComparator
{
	private final ListFiles view;
	private final ViewerComparator elementsorter = new JavaElementComparator();

	private int sortcolumn;
	private boolean reversesort;

	public TreeSorter(ListFiles view) {
		this.view = view;
	}

	void addColumn(final TreeColumn column, final int columnidx)
	{
		column.addSelectionListener(new SelectionListener()
		{
			@Override
			public void widgetSelected(SelectionEvent e)
			{
				toggleSortColumn(columnidx);
				setSortColumnAndDirection(column, isReverseSort() ? SWT.DOWN : SWT.UP);
				view.refreshViewer();
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) { }
		});
	}

	void setSortColumnAndDirection(TreeColumn sortColumn, int direction) {
		sortColumn.getParent().setSortColumn(sortColumn);
		sortColumn.getParent().setSortDirection(direction);
	}

	public int getSortColumn() {
		return sortcolumn;
	}

	public boolean isReverseSort() {
		return reversesort;
	}

	public void toggleSortColumn(int column) {
		if (sortcolumn == column) {
			reversesort = !reversesort;
		}
		else {
			reversesort = false;
			sortcolumn = column;
		}
	}

	@Override
	public int compare(Viewer viewer, Object e1, Object e2)
	{
		ITreeNode node1 = (ITreeNode) e1;
		ITreeNode node2 = (ITreeNode) e2;

		int res = 0;

		switch (getSortColumn())
		{
			case ListFiles.COLUMN_ELEMENT:
				res = node1.getName().compareTo(node2.getName());
				break;
			case ListFiles.COLUMN_NUMBER:
				res = (int) (node1.getChildren().size() - node2.getChildren().size());
				break;
		}

		if (res == 0)
			res = elementsorter.compare(viewer, e1, e2);
		else
			res = isReverseSort() ? -res : res;

		return res;
	}
}


Cheers, Very Happy
Previous Topic:Scrolled Form
Next Topic:SourceViewer undo support
Goto Forum:
  


Current Time: Wed Jul 30 01:14:34 EDT 2014

Powered by FUDForum. Page generated in 0.33813 seconds