Java Tutorial/SWT/TreeViewer

Материал из Java эксперт
Версия от 15:19, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Create CheckBoxTreeView and react to CheckStateListener

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class CheckFileTreeViewer {
  public static void main(String[] args) {
    CheckFileTree main = new CheckFileTree();
  }
}
class CheckFileTree extends ApplicationWindow{
  public CheckFileTree() {
    super(null);
    // Don"t return from open() until window closes
    setBlockOnOpen(true);
    open();
    Display.getCurrent().dispose();
  }
  protected void configureShell(Shell shell) {
    super.configureShell(shell);
    shell.setSize(400, 400);
  }
  /**
   * Creates the main window"s contents
   *
   * @param parent the main window
   * @return Control
   */
  protected Control createContents(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    composite.setLayout(new GridLayout(1, false));
    // Create the tree viewer to display the file tree
    final CheckboxTreeViewer tv = new CheckboxTreeViewer(composite);
    tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
    tv.setContentProvider(new FileTreeContentProvider());
    tv.setLabelProvider(new FileTreeLabelProvider());
    tv.setInput("root"); // pass a non-null that will be ignored
    // When user checks a checkbox in the tree, check all its children
    tv.addCheckStateListener(new ICheckStateListener() {
      public void checkStateChanged(CheckStateChangedEvent event) {
        if (event.getChecked()) {
          tv.setSubtreeChecked(event.getElement(), true);
        }
      }
    });
    return composite;
  }
}

class FileTreeContentProvider implements ITreeContentProvider {
  public Object[] getChildren(Object arg0) {
    return ((File) arg0).listFiles();
  }
  public Object getParent(Object arg0) {
    return ((File) arg0).getParentFile();
  }
  public boolean hasChildren(Object arg0) {
    Object[] obj = getChildren(arg0);
    return obj == null ? false : obj.length > 0;
  }
  public Object[] getElements(Object arg0) {
    return File.listRoots();
  }
  public void dispose() {
  }
  public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
  }
}
class FileTreeLabelProvider implements ILabelProvider {
  private List listeners;
  private Image file;
  private Image dir;
  public FileTreeLabelProvider() {
    listeners = new ArrayList();
    try {
      file = new Image(null, new FileInputStream("images/file.gif"));
      dir = new Image(null, new FileInputStream("images/directory.gif"));
    } catch (FileNotFoundException e) {
    }
  }
  public Image getImage(Object arg0) {
    return ((File) arg0).isDirectory() ? dir : file;
  }
  public String getText(Object arg0) {
    String text = ((File) arg0).getName();
    if (((File) arg0).getName().length() == 0) {
      text = ((File) arg0).getPath();
    }
    return text;
  }
  public void addListener(ILabelProviderListener arg0) {
    listeners.add(arg0);
  }
  public void dispose() {
    // Dispose the images
    if (dir != null)
      dir.dispose();
    if (file != null)
      file.dispose();
  }
  public boolean isLabelProperty(Object arg0, String arg1) {
    return false;
  }
  public void removeListener(ILabelProviderListener arg0) {
    listeners.remove(arg0);
  }
}





Create TreeView based on your own tree node structure

import java.util.Vector;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class TreeViewBasedOnNode {
  static Display display = new Display();
  static Shell shell = new Shell(display);
  static final Tree tree = new Tree(shell, SWT.BORDER);
  static Vector nodes = new Vector();
  public static void traditional() {
    for (int i = 0; nodes != null && i < nodes.size(); i++) {
      Node node = (Node) nodes.elementAt(i);
      addNode(null, node);
    }
  }
  private static void addNode(TreeItem parentItem, Node node) {
    TreeItem item = null;
    if (parentItem == null)
      item = new TreeItem(tree, SWT.NONE);
    else
      item = new TreeItem(parentItem, SWT.NONE);
    item.setText(node.getName());
    Vector subs = node.getSubCategories();
    for (int i = 0; subs != null && i < subs.size(); i++)
      addNode(item, (Node) subs.elementAt(i));
  }
  public static void main(String[] args) {
    Node category = new Node("A", null);
    nodes.add(category);
    category = new Node("a1", category);
    new Node("a11", category);
    new Node("a12", category);
    category = new Node("B", null);
    nodes.add(category);
    new Node("b1", category);
    new Node("b2", category);
    TreeViewer treeViewer = new TreeViewer(tree);
    treeViewer.setContentProvider(new MyTreeContentProvider());
    treeViewer.setLabelProvider(new MyLabelProvider());
    treeViewer.setInput(nodes);
    tree.setSize(300, 200);
    shell.setSize(300, 200);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
}
class MyLabelProvider implements ILabelProvider {
  public String getText(Object element) {
    return ((Node) element).getName();
  }
  public Image getImage(Object arg0) {
    return null;
  }
  public void addListener(ILabelProviderListener arg0) {
  }
  public void dispose() {
  }
  public boolean isLabelProperty(Object arg0, String arg1) {
    return false;
  }
  public void removeListener(ILabelProviderListener arg0) {
  }
}

class MyTreeContentProvider implements ITreeContentProvider{
  public Object[] getChildren(Object parentElement) {
    Vector subcats = ((Node) parentElement).getSubCategories();
    return subcats == null ? new Object[0] : subcats.toArray();
  }
  public Object getParent(Object element) {
    return ((Node) element).getParent();
  }
  public boolean hasChildren(Object element) {
    return ((Node) element).getSubCategories() != null;
  }
  public Object[] getElements(Object inputElement) {
    if (inputElement != null && inputElement instanceof Vector) {
      return ((Vector) inputElement).toArray();
    }
    return new Object[0];
  }
  public void dispose() {
  }
  public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
  }
}

class Node {
  private String name;
  private Vector subCategories;
  private Node parent;
  public Node(String name, Node parent) {
    this.name = name;
    this.parent = parent;
    if (parent != null)
      parent.addSubCategory(this);
  }
  public Vector getSubCategories() {
    return subCategories;
  }
  private void addSubCategory(Node subcategory) {
    if (subCategories == null)
      subCategories = new Vector();
    if (!subCategories.contains(subcategory))
      subCategories.add(subcategory);
  }
  public String getName() {
    return name;
  }
  public Node getParent() {
    return parent;
  }
}





Tree Viewers

JFace wraps SWT"s Tree widget with a class called TreeViewer.

Creating a TreeViewer

TreeViewer treeViewer = new TreeViewer(shell);



Create a TreeViewer to wrap an existing Tree control, like this:
Tree tree = new Tree(shell, SWT.SINGLE);
TreeViewer treeViewer = new TreeViewer(tree);





Using a TreeViewer

The general way to use a TreeViewer:

  1. Creating a TreeViewer
  2. Creating a content provider class and setting it on the TreeViewer using setContentProvider()
  3. Creating a label provider class and setting it on the TreeViewer using setLabelProvider()
  4. Setting the root input for the tree using setInput()



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class FileTreeWindowApplication {
  public static void main(String[] args) {
    FileTreeWindow main = new FileTreeWindow();
  }
}
class FileTreeWindow extends ApplicationWindow {
  public FileTreeWindow() {
    super(null);
    // Don"t return from open() until window closes
    setBlockOnOpen(true);
    open();
    Display.getCurrent().dispose();
  }
  protected void configureShell(Shell shell) {
    super.configureShell(shell);
    shell.setSize(400, 400);
  }
  protected Control createContents(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    composite.setLayout(new FillLayout());
    final TreeViewer tv = new TreeViewer(composite);
    tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
    tv.setContentProvider(new FileTreeContentProvider());
    tv.setLabelProvider(new FileTreeLabelProvider());
    tv.setInput("root");
    return composite;
  }
}
class FileTreeContentProvider implements ITreeContentProvider {
  public Object[] getChildren(Object arg0) {
    return ((File) arg0).listFiles();
  }
  public Object getParent(Object arg0) {
    return ((File) arg0).getParentFile();
  }
  public boolean hasChildren(Object arg0) {
    Object[] obj = getChildren(arg0);
    return obj == null ? false : obj.length > 0;
  }
  public Object[] getElements(Object arg0) {
    return File.listRoots();
  }
  public void dispose() {
  }
  public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
  }
}
class FileTreeLabelProvider implements ILabelProvider {
  private List listeners;
  private Image file;
  private Image dir;
  public FileTreeLabelProvider() {
    listeners = new ArrayList();
    try {
      file = new Image(null, new FileInputStream("images/file.gif"));
      dir = new Image(null, new FileInputStream("images/directory.gif"));
    } catch (FileNotFoundException e) {
    }
  }
  public Image getImage(Object arg0) {
    return ((File) arg0).isDirectory() ? dir : file;
  }
  public String getText(Object arg0) {
    String text = ((File) arg0).getName();
    if (((File) arg0).getName().length() == 0) {
      text = ((File) arg0).getPath();
    }
    return text;
  }
  public void addListener(ILabelProviderListener arg0) {
    listeners.add(arg0);
  }
  public void dispose() {
    // Dispose the images
    if (dir != null)
      dir.dispose();
    if (file != null)
      file.dispose();
  }
  public boolean isLabelProperty(Object arg0, String arg1) {
    return false;
  }
  public void removeListener(ILabelProviderListener arg0) {
    listeners.remove(arg0);
  }
}