Support free tutorials:











vogella training Training Books



Eclipse JFace Tree - Tutorial

Lars Vogel

Version 3.3

15.10.2013

Revision History
Revision 0.1 - 3.3 22.08.2010 - 15.10.2013 Lars
Vogel
created, bug fixes and enhancements

Eclipse JFace TreeViewer tutorial

This tutorial explains the usage of Eclipse JFace TreeViewer. It also shows the usage of a StyledLabelProvider. It is based on Eclipse 4.3. (Kepler).


Table of Contents

1. Prerequisites
2. JFace TreeViewer
2.1. Using viewers to display a tree
2.2. Selection and double-click listener
3. Exercise: File browser via a TreeViewer
3.1. Create a new application
3.2. Add an image file
3.3. Create a part
3.4. Validate
4. Learn more about Eclipse 4 RCP development
5. Support free vogella tutorials
5.1. Thank you
5.2. Questions and Discussion
6. Links and Literature
6.1. Source Code
6.2. JFace Resources
6.3. vogella Resources

Get the book Eclipse IDE book

1. Prerequisites

Please see Introduction to JFace for an introduction to the concepts behind this example.

For an example on how to build JFace Tables please see JFace Table Tutorial.

2. JFace TreeViewer

2.1. Using viewers to display a tree

The TreeViewer class provides viewer support for displaying trees. The usage of this class is similar to the TableViewer class.

The main difference is that the TreeViewer class requires a structured content provider. Typically your content provider has to implement the ITreeContentProvider interface to be used with your TreeViewer class.

The usage of the TreeViewer class is demonstrated in Section 3, “Exercise: File browser via a TreeViewer”.

2.2. Selection and double-click listener

JFace allows you to access the SWT controls to define listeners on your viewer. For example you can add a SelectionListener implementation to the SWT control which is wrapped in the JFace object. The following code snippet demonstrates how to expand a tree with a mouse click.

// the viewer field is an already configured TreeViewer
Tree tree = (Tree) viewer.getControl();
tree.addSelectionListener(new SelectionAdapter() {
  @Override
  public void widgetSelected(SelectionEvent e) {
    TreeItem item = (TreeItem) e.item;
      if (item.getItemCount() > 0) {
        item.setExpanded(!item.getExpanded());
        // update the viewer
        viewer.refresh();
      }
    }
}); 

Viewers allows you to add certain listeners directly to them. The following example shows how to expand an instance of a TreeViewer with a double click.

viewer.addDoubleClickListener(new IDoubleClickListener() {
  @Override
  public void doubleClick(DoubleClickEvent event) {
    TreeViewer viewer = (TreeViewer) event.getViewer();
    IStructuredSelection thisSelection = (IStructuredSelection) event.getSelection(); 
    Object selectedNode = thisSelection.getFirstElement(); 
    viewer.setExpandedState(selectedNode,
        !viewer.getExpandedState(selectedNode));
  }
}); 

3. Exercise: File browser via a TreeViewer

Note

This exercise is optional.

3.1. Create a new application

This exercise is a stand-alone exercise and can be used to repeat the steps of creating an Eclipse 4 application.

Use the Eclipse 4 wizard from FileNewOther...Eclipse 4Eclipse 4 Application Project to create a new Eclipse 4 application without sample data called com.example.e4.filebrowser.

The important selection in the last wizard page is highlighted in the following screenshot.

Empty content

3.2. Add an image file

Download or create an icon called folder.png and place it into the "icons" folder of your plug-in.

You find an example icon under the following URL: Folder icon.

This icon is taken from the following icon collection: FamFamFam icons

3.3. Create a part

Add a part stack with a part to your application model and display a TreeViewer in this part.

Implement a class for the ITreeContentProvider interface which allows you to browse the file system. Review the Javadoc of this class to understand the methods of this interface.

Also implement your custom LabelProvider for the tree.

Use viewer.setInput(File.listRoots()); to set the initial input to the viewer.

The following listing contains an example implementation for this exercise. It assumes that you added the "folder.png" icon to the "icons" folder. It also demonstrates the usage of a StyledLabelProvider.

package com.example.e4.filebrowser.parts;

import java.io.File;
import java.net.URL;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;

public class FileBrowserPart {
  private TreeViewer viewer;
  private Image image;

  @PostConstruct
  public void createControls(Composite parent) {
    createImage();
    viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
    viewer.setContentProvider(new ViewContentProvider());
    viewer.setLabelProvider(new ViewLabelProvider());
    viewer.setInput(File.listRoots());
  }

  private void createImage() {
    Bundle bundle = FrameworkUtil.getBundle(ViewLabelProvider.class);
    URL url = FileLocator.find(bundle, new Path("icons/folder.png"), null);
    ImageDescriptor imageDcr = ImageDescriptor.createFromURL(url);
    this.image = imageDcr.createImage();
  }

  class ViewContentProvider implements ITreeContentProvider {
    public void inputChanged(Viewer v, Object oldInput, Object newInput) {
    }

    @Override
    public void dispose() {
    }

    @Override
    public Object[] getElements(Object inputElement) {
      return (File[]) inputElement;
    }

    @Override
    public Object[] getChildren(Object parentElement) {
      File file = (File) parentElement;
      return file.listFiles();
    }

    @Override
    public Object getParent(Object element) {
      File file = (File) element;
      return file.getParentFile();
    }

    @Override
    public boolean hasChildren(Object element) {
      File file = (File) element;
      if (file.isDirectory()) {
        return true;
      }
      return false;
    }

  }

  class ViewLabelProvider extends StyledCellLabelProvider {
    @Override
    public void update(ViewerCell cell) {
      Object element = cell.getElement();
      StyledString text = new StyledString();
      File file = (File) element;
      if (file.isDirectory()) {
        text.append(getFileName(file));
        cell.setImage(image);
        String[] files = file.list();
        if (files != null) {
          text.append(" (" + files.length + ") ",
              StyledString.COUNTER_STYLER);
        }
      } else {
        text.append(getFileName(file));
      }
      cell.setText(text.toString());
      cell.setStyleRanges(text.getStyleRanges());
      super.update(cell);

    }

    private String getFileName(File file) {
      String name = file.getName();
      return name.isEmpty() ? file.getPath() : name;
    }
  }

  @Focus
  public void setFocus() {
    viewer.getControl().setFocus();
  }

  @PreDestroy
  public void dispose() {
    image.dispose();
  }
} 

Link from your part in the application model to your new class.

3.4. Validate

Start your new application ensure that you see the content of your file system in your tree.

4. Learn more about Eclipse 4 RCP development

I hope you enjoyed this tutorial. You find this tutorial and much more information also in the Eclipse 4 RCP book from this author.

5. Support free vogella tutorials

Maintaining high quality free online tutorials is a lot of work. Please support free tutorials by donating or by reporting typos and factual errors.

5.1. Thank you

Please consider a contribution if this article helped you.

Flattr this

5.2. Questions and Discussion

If you find errors in this tutorial, please notify me (see the top of the page). Please note that due to the high volume of feedback I receive, I cannot answer questions to your implementation. Ensure you have read the vogella FAQ as I don't respond to questions already answered there.

6. Links and Literature

6.1. Source Code

Source Code of Examples

6.2. JFace Resources

http://www.eclipse.org/articles/Article-Table-viewer/table_viewer.html Building and delivering a table editor with SWT/JFace

http://wiki.eclipse.org/index.php/JFaceSnippets JFace snippets, e.g. small code examples

6.3. vogella Resources

vogella Training Android and Eclipse Training from the vogella team

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java, compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put all your files in a distributed version control system