I like my trees filtered (Eclipse FilteredTree )

The class org.eclipse.ui.dialogs.FilteredTree is an easy way to filter tree elements. It provides automatically a text field for restricting the entries in the table.

For example a simple application could look like the following.

FilteredTree

The following is a small description how to use this (using a Eclipse RCP example).

Create a new Eclipse RCP project, e.g. de.vogella.rcp.intro.filteredtree, using the “Eclipse application with a view” template.

Create the following content and lable provider (they are dead simple).

package de.vogella.rcp.intro.filteredtree;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

public class TreeContentProvider implements ITreeContentProvider {

	@Override
	public Object[] getChildren(Object arg0) {
		return null;
	}

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

	@Override
	public boolean hasChildren(Object arg0) {
		return false;
	}

	@Override
	public Object[] getElements(Object arg0) {
		String[] array = { "Habelman", "Hans", "Jim", "Joe" };
		return array;
	}

	@Override
	public void dispose() {
	}

	@Override
	public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
	}

}

package de.vogella.rcp.intro.filteredtree;

import org.eclipse.jface.viewers.LabelProvider;

public class TreeLabelProvider extends LabelProvider {
	@Override
	public String getText(Object element) {
		String name = (String) element;
		return name;
	}
}

Then change the View.java to the following to use the FilteredTree in your application.

package de.vogella.rcp.intro.filteredtree;

import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.part.ViewPart;

public class View extends ViewPart {
	public static final String ID = "de.vogella.intro.rcp.filteredtree.view";
	private TreeViewer viewer;

	public void createPartControl(Composite parent) {
		PatternFilter filter = new PatternFilter();
		FilteredTree tree = new FilteredTree(parent, SWT.MULTI | SWT.H_SCROLL
				| SWT.V_SCROLL, filter, true);

		viewer = tree.getViewer();
		viewer.setContentProvider(new TreeContentProvider());
		viewer.setLabelProvider(new TreeLabelProvider());
		viewer.setInput(getViewSite());
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Eclipse. Bookmark the permalink.