JTree Utilities : Tree « Swing JFC « Java






JTree Utilities

   
/**
 * Class: TreeUtil
 * Description: A simple utility class for dealing with Trees
 * @author Le Cuong Nguyen
 **/
//package atnf.atoms.mon.util;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import java.util.StringTokenizer;

import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTree;
import javax.swing.event.EventListenerList;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class TreeUtil implements ActionListener, TreeSelectionListener {
  protected DefaultMutableTreeNode itsRootNode = null;
  protected JMenuItem itsRootMenu = null;

  // Should really do this with an object encompassing the nodes and data
  // with only on map. But this is easier...
  protected Hashtable<String, Object> itsMap = new Hashtable<String, Object>();
  protected Hashtable<String, Object> itsTreeMap = new Hashtable<String, Object>();

  public static final int TREE = 7654;
  public static final int MENU = 7655;

  // Want to do stuff with ActionListeners
  private EventListenerList itsListeners = new EventListenerList();

  public TreeUtil(String name, Object root) {
    itsMap.put(name, root);
    itsRootNode = new DefaultMutableTreeNode(name);
    itsTreeMap.put(name, itsRootNode);
  }

  public TreeUtil(String name) {
    itsMap.put(name, new Object());
    itsRootNode = new DefaultMutableTreeNode(name);
    itsTreeMap.put(name, itsRootNode);
  }

  public void addNode(String name) {
    addNode(name, new Object());
  }

  public void addNode(String name, Object obj) {
    itsMap.put(name, obj);
    DefaultMutableTreeNode tempNode = itsRootNode;
    StringTokenizer tok = new StringTokenizer(name, ".");
    String currentName = null;
    while (tok.hasMoreTokens()) {
      String myTok = tok.nextToken();
      currentName = (currentName == null) ? myTok : currentName + "."
          + myTok;
      boolean createNew = true;
      for (int j = 0; j < tempNode.getChildCount(); j++) {
        DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) tempNode
            .getChildAt(j);
        if (childNode.toString().equals(myTok)) {
          tempNode = childNode;
          createNew = false;
          break;
        }
      }
      if (createNew) {
        DefaultMutableTreeNode aNode = new DefaultMutableTreeNode(myTok);
        itsTreeMap.put(currentName, aNode);
        // Let's give some consideration to where in the tree we place
        // the new node.
        // We want any nodes with children to be listed first, in
        // alphabetical order.
        // Then come nodes with no children, in alphabetical order.
        if (tok.hasMoreTokens()) {
          // This node is not a leaf node
          int targeti;
          for (targeti = 0; targeti < tempNode.getChildCount(); targeti++) {
            TreeNode bNode = tempNode.getChildAt(targeti);
            if (bNode.isLeaf()
                || bNode.toString().compareToIgnoreCase(myTok) > 0) {
              break;
            }
          }
          tempNode.insert(aNode, targeti);
        } else {
          // This node is a leaf node
          int targeti;
          for (targeti = 0; targeti < tempNode.getChildCount(); targeti++) {
            TreeNode bNode = tempNode.getChildAt(targeti);
            if (bNode.isLeaf()
                && bNode.toString().compareToIgnoreCase(myTok) > 0) {
              break;
            }
          }
          tempNode.insert(aNode, targeti);
        }
        tempNode = aNode;
      }
    }
  }

  public void addChildNode(DefaultMutableTreeNode parent, String name) {
    String realName = parent.getUserObject().toString() + "." + name;
    addNode(realName);
  }

  public Object getNodeObject(String name) {
    return itsMap.get(name);
  }

  public void setNodeObject(String node, Object data) {
    itsMap.put(node, data);
  }

  public String[] getAllNodes() {
    return toStringArray(itsMap.keySet().toArray());
  }

  public static String[] toStringArray(Object[] data) {
    String[] res = new String[data.length];
    for (int i = 0; i < res.length; i++) {
      res[i] = (String) (data[i]);
    }
    return res;
  }

  public DefaultMutableTreeNode getNode(String name) {
    return (DefaultMutableTreeNode) itsTreeMap.get(name);
  }

  public DefaultMutableTreeNode getRootNode() {
    return itsRootNode;
  }

  /**
   * Make a Menu structure, without the root node. The children of the root
   * node will be added to the specified menu element.
   */
  public void getMenus(JMenu menu) {
    int numChild = itsRootNode.getChildCount();
    for (int i = 0; i < numChild; i++) {
      menu.add(getMenus(
          (DefaultMutableTreeNode) itsRootNode.getChildAt(i), menu));
    }
  }

  /**
   * Makes menus from the root node
   */
  public JMenuItem getMenus() {
    JMenu rootMenu = new JMenu(itsRootNode.getUserObject().toString());
    rootMenu.setActionCommand("TreeMenu");
    rootMenu.addActionListener(this);
    return getMenus(itsRootNode, rootMenu);
  }

  /** Creates the menus by using recursion */
  public JMenuItem getMenus(DefaultMutableTreeNode node, JMenu parentMenu) {
    String name = node.getUserObject().toString();
    int numChild = node.getChildCount();
    if (numChild < 1) {
      JMenuItem tempMenu = new JMenuItem(name);
      tempMenu.setActionCommand(parentMenu.getActionCommand() + "."
          + name);
      tempMenu.addActionListener(this);
      return tempMenu;
    }
    JMenu tempMenu = new JMenu(name);
    tempMenu.setActionCommand(parentMenu.getActionCommand() + "." + name);
    tempMenu.addActionListener(this);
    for (int i = 0; i < numChild; i++) {
      tempMenu.add(getMenus((DefaultMutableTreeNode) node.getChildAt(i),
          tempMenu));
    }
    return tempMenu;
  }

  public JTree getTree() {
    return getTree(itsRootNode);
  }

  public JTree getTree(DefaultMutableTreeNode node) {
    JTree tree = new JTree(node);
    // tree.addTreeSelectionListener(this);
    return tree;
  }

  public void addActionListener(ActionListener listener) {
    itsListeners.add(ActionListener.class, listener);
  }

  public void removeActionListener(ActionListener listener) {
    itsListeners.remove(ActionListener.class, listener);
  }

  public void fireActionEvent(ActionEvent ae) {
    Object[] listeners = itsListeners.getListenerList();
    for (int i = 0; i < listeners.length; i += 2) {
      if (listeners[i] == ActionListener.class) {
        ((ActionListener) listeners[i + 1]).actionPerformed(ae);
      }
    }
  }

  public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();
    int idx = cmd.indexOf('.');
    cmd = cmd.substring(++idx, cmd.length());
    fireActionEvent(new ActionEvent(this, MENU, cmd));
  }

  public void valueChanged(TreeSelectionEvent e) {
    TreePath path = e.getPath();
    Object[] items = path.getPath();
    if (items.length < 1) {
      return;
    }
    String cmd = "";
    for (int i = 0; i < items.length; i++) {
      cmd = cmd + "." + items[i].toString();
    }
    if (cmd.length() > 0) {
      cmd = cmd.substring(1);
    }
    fireActionEvent(new ActionEvent(this, TREE, cmd));
  }

  /*
   * public ArrayList search(String pattern) { ArrayList res = new
   * ArrayList(); try { RE re = new RE(pattern, RE.MATCH_CASEINDEPENDENT);
   * Iterator it = itsTreeMap.keySet().iterator(); while (it.hasNext()) {
   * String key = (String)it.next(); if (re.match(key)) res.add(key); } }
   * catch (Exception e) {e.printStackTrace();} return res; }
   */

  public TreePath makeTreePath(String path) {
    return makeTreePath(path, itsRootNode);
  }

  public static TreePath makeTreePath(String path,
      DefaultMutableTreeNode parentNode) {
    DefaultMutableTreeNode tempNode = parentNode;
    TreePath res = new TreePath(parentNode);
    StringTokenizer tok = new StringTokenizer(path, ".");
    String currentPath = null;
    while (tok.hasMoreTokens()) {
      String myTok = tok.nextToken();
      currentPath = (currentPath == null) ? myTok : currentPath + "."
          + myTok;
      for (int j = 0; j < tempNode.getChildCount(); j++) {
        DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) tempNode
            .getChildAt(j);
        if (childNode.toString().equals(myTok)) {
          tempNode = childNode;
          res = res.pathByAddingChild(tempNode);
          break;
        }
      }
    }
    return res;
  }

  public static String pathToString(TreePath path) {
    if (path == null) {
      return null;
    }
    Object[] obj = path.getPath();
    String res = "";
    for (int i = 0; i < obj.length; i++) {
      res = res + "." + obj[i].toString();
    }
    if (res.length() > 0) {
      res = res.substring(1);
    }
    return res;
  }
}

   
    
    
  








Related examples in the same category

1.Build a tree based on DefaultMutableTreeNodeBuild a tree based on DefaultMutableTreeNode
2.Add Tree to JScrollPaneAdd Tree to JScrollPane
3.Genealogy TreeGenealogy Tree
4.Tree LinesTree Lines
5.DefaultMutableTreeNode Node Tree SampleDefaultMutableTreeNode Node Tree Sample
6.Display a file system in a JTree viewDisplay a file system in a JTree view
7.implements TreeSelectionListener to create your own listenerimplements TreeSelectionListener  to create your own listener
8.File folder Tree with iconsFile folder Tree with icons
9.File Tree with Popup MenuFile Tree with Popup Menu
10.File Tree with TooltipsFile Tree with Tooltips
11.Ancestor Tree with IconsAncestor Tree with Icons
12.Tree Icon DemoTree Icon Demo
13.DefaultMutableTreeNode and user objectDefaultMutableTreeNode and user object
14.Display user object in a treeDisplay user object in a tree
15.Tree Expand Event DemoTree Expand Event Demo
16.Tree: Drag and DropTree: Drag and Drop
17.Tree open IconTree open Icon
18.Traverse TreeTraverse Tree
19.Tree based on Array structureTree based on Array structure
20.Tree will Expand event and listenerTree will Expand event and listener
21.Set the Tree LineSet the Tree Line
22.Tree Selection RowTree Selection Row
23.JTree.DynamicUtilTreeNode.createChildrenJTree.DynamicUtilTreeNode.createChildren
24.Install ToolTips for Tree (JTree)Install ToolTips for Tree (JTree)
25.Tree Expand Event Demo 2Tree Expand Event Demo 2
26.A tree with componentA tree with component
27.A sample component for dragging and dropping a collection of files into a tree.A sample component for dragging and dropping a collection of files into a tree.
28.DnD (drag and drop)JTree code DnD (drag and drop)JTree code
29.Build a tree and populate it from hashtablesBuild a tree and populate it from hashtables
30.A simple test to see how we can build a tree and populate itA simple test to see how we can build a tree and populate it
31.Installs custom iconsInstalls custom icons
32.Build a tree and customize its iconsBuild a tree and customize its icons
33.Displaying Hierarchical Data within a JTreeDisplaying Hierarchical Data within a JTree
34.Add and remove tree Node and expand the tree node
35.File System Tree
36.TreeExpansionListener and TreeExpansionEventTreeExpansionListener and TreeExpansionEvent
37.Enabling and Disabling Multiple Selections in a JTree Component
38.Allow only a single node to be selected (default)
39.Allow selection to span one vertical contiguous set of visible nodes
40.Allow multiple selections of visible nodes
41.Setting the Row Height of a JTree
42.All rows will be given 15 pixels of height
43.Have the row height for each row computed individually
44.Flush the internal cache of Row height
45.Preventing Expansion or Collapse of a Node in a JTree: override JTree.setExpandedState()
46.Removing a Node to a JTree Component
47.JTree root cannot be removed with removeNodeFromParent(), use DefaultTreeModel.setRoot() to remove the root
48.Listening for Expansion and Collapse Events in a JTree Component
49.Expansion and Collapse Events in a JTree are fired before a node is expanded or collapsed can be vetoed, thereby preventing the operation.
50.Creating a JTree Component
51.Changing and Removing the Default Icons in a JTree Component
52.Use UIManager to change the default icon for JTree
53.Getting the Selected Nodes in a JTree Component
54.Visiting All the Nodes in a JTree Component
55.Traverse all expanded nodes in tree
56.Finding a Node in a JTree Component
57.Search backward from last visible row looking for any visible node whose name starts with prefix.
58.Find the path regardless of visibility that matches the specified sequence of names
59.Adding a Node to a JTree Component
60.Returns a TreePath containing the specified node.
61.Converting All Nodes in a JTree Component to a TreePath Array
62.Get path for all expanded or not expanded tree pathes
63.Expanding or Collapsing All Nodes in a JTree Component
64.Preventing the Expansion or Collapse of a Node in a JTree Component
65.Listening for Selection Events in a JTree Component
66.Have a popup attached to a JTree
67.Deleting nodes from JTree
68.Adding editable nodes to JTree
69.Searching node in a JTree
70.Drag and drop of a group of files into a tree
71.JTree drag and drop utilites
72.Expand All for a tree path
73.Get tree path from TreeNode
74.Expand JTree