JTree class notes - Musings

By: Nicholas Duchon.

You can use the following classes to create a fairly simple tree. In the example I did in an earlier semester, I read in the entire data file, then passed a handle to the structure to create the tree. The example uses the following classes to create and display the tree:

The traversal of the data file should be the same as the tree structure you wish to create.

Here's an example of the sort of code I think will work nicely. In this case, we had the following classes:

The data structure in this case was an array of Furniture, so it could be sorted very nicely and we just had to step through the array in order to create the tree.

The tree items were arranged according to the following levels: Manufacturer --> Style --> Type --> Furniture item

The code has the concepts of:

When one of those changes, a new node at that level is created in the tree.

   public void addManTree (DefaultMutableTreeNode top) {
      sortOn (TYPE);
      sortOn (STYLE);
      sortOn (MAN);
      DefaultMutableTreeNode d = null, s = null, t = null;
      Manufacturer m = null;
      String style   = null;
      String type    = null;
      for (Furniture f: furs) {
         if (f.mf != m) {
            m = f.mf;
            d = new DefaultMutableTreeNode(m.name);
            top.add (d);
         } // end if new manufacturer
         if (!(f.style.equals (style))) {
            style = f.style;
            s = new DefaultMutableTreeNode(f.style);
            d.add (s);
         } // end if new style
         if (!(f.type.equals (type))) {
            type = f.type;
            t = new DefaultMutableTreeNode(f.type);
            s.add (t);
         } // end if new style
         s.add (t);
         t.add (new DefaultMutableTreeNode("Index: " + f.index + ", Price: " + f.price));
      } // end for each manufacturer
   } // end addManTree


JTree Example 1


Code for example 1:

// File: JTreeExample
// Date: Sep 20, 2012
// Author: Nicholas Duchon
// Purpose: a quick demonstration of populating and presenting a JTree
//   Node constains data a links to child Node's
//   createDataTree creates a tree structure using Node elements
//   createNodes recursively transfer the tree to a JTree, using DefaultMutableTreeNode
//      data is just the String data in Node instances.
// Notes -
//   NodeIF means that the for loop in createNodes only needs to know that getChildren
//     returns an ArrayList <NodeIF> for iteration
//   The display of the JTree uses the toString method of the objects - Node's in this case.

import java.util.ArrayList;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JTree;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import java.awt.BorderLayout;

public class JTreeExample {
 
   public static void main (String args []) {
      JTreeExample j = new JTreeExample ();
   } // end main

   public JTreeExample () {
      Node top = createDataTree ();
      DefaultMutableTreeNode jtTop = createNodes(top);
      JTree tree = new JTree(jtTop);
      JScrollPane treeView = new JScrollPane(tree);
      JFrame jf = new JFrame ("JTree example 1 - ND");
      jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      jf.setSize (230, 400);
      jf.setLocationRelativeTo (null);
      jf.setVisible (true);
      jf.add (treeView, BorderLayout.CENTER);
      jf.validate ();
  
} // end constructor

   DefaultMutableTreeNode createNodes (NodeIF t) {
      DefaultMutableTreeNode top = new DefaultMutableTreeNode (t);
      for (NodeIF n: t.getChildren()) top.add (createNodes (n));
      return top;
  
} // end createNodes
 
   Node createDataTree () {
      Node t, u, v, w, x;
      Node z = new Node ("zero");
     
      z.children.add (t = new Node ("one A"));
      t.children.add (u = new Node ("twoA A"));
      t.children.add (u = new Node ("twoA B"));
      t.children.add (u = new Node ("twoA C"));
      u.children.add (w = new Node ("threeAC A"));
      u.children.add (w = new Node ("threeAC B"));
      t.children.add (u = new Node ("twoA D"));
      z.children.add (t = new Node ("one B"));
      t.children.add (u = new Node ("twoB A"));
      t.children.add (u = new Node ("twoB B"));
      u.children.add (w = new Node ("threeBB A"));
      u.children.add (w = new Node ("threeBB B"));
      w.children.add (x = new Node ("threeBBB A"));
      w.children.add (x = new Node ("threeBBB B"));
      t.children.add (u = new Node ("twoB C"));
      t.children.add (u = new Node ("twoB D"));
      z.children.add (t = new Node ("one C"));
      t.children.add (u = new Node ("twoC A"));
      t.children.add (u = new Node ("twoC B"));
      t.children.add (u = new Node ("twoC C"));
      t.children.add (u = new Node ("twoC D"));
      z.children.add (t = new Node ("one D"));
      t.children.add (u = new Node ("twoD A"));
      t.children.add (u = new Node ("twoD B"));
      t.children.add (u = new Node ("twoD C"));
      t.children.add (u = new Node ("twoD D"));
      return z;
  
} // end createDataTree
} // end class JTreeExample

interface NodeIF {
   public ArrayList <NodeIF> getChildren ();
} // end NodeIF

class Node implements NodeIF {
   String data;
   ArrayList <NodeIF> children = new ArrayList <NodeIF> ();

   public Node (String s) {data = s;
}
  
   public ArrayList <NodeIF> getChildren () {
      return children;

   }   

   public String toString () {
      return data;

   }
} // end Node


JTree Example 2

Here's a fairly simple example using a JTree to display a data structure based on a tree using ArrayLists of child nodes:

Code for Example 2:

// File: JTreeExample2
// Date: Jul 19, 2013
// Author: Nicholas Duchon
// Purpose: a quick demonstration of populating and presenting a JTree
//   createDataTree creates a tree structure directly as a JTree using DefaultMutableTreeNode's as elements of the tree
//   the DMTN references Element's, which are really any Object you wish to define.
//   Display - this code shows how to display the results of various traversals also.
//   Also added JSplitPane's to present traversals in GUI's
// Notes -
//   DMTN only has one set of children at each node, so if your project is more complex, you will need to fix this somehow.

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JTree;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.Enumeration; // used for display, note that this is normally generic, but DMTN enumerations are NOT!

public class JTreeExample2 extends JFrame {
   public static final long serialVersionUID = 1234L;
   int paneCount = 5;
   JSplitPane jsppA;
   JSplitPane jsppB;
   JSplitPane jsppC;
   JSplitPane jsppD;
   JFrame jf;

   public static void main (String args []) {
      JTreeExample2 j = new JTreeExample2 ();
   } // end main

   @SuppressWarnings ("unchecked")
   public JTreeExample2 () {
      DefaultMutableTreeNode root = createNodes ();
      JTree tree = new JTree(root);
  
  
      JScrollPane treeView = new JScrollPane(tree);
  
      JTextArea jtaA = new JTextArea ();
      JScrollPane jspA = new JScrollPane (jtaA);
  
      JTextArea jtaB = new JTextArea ();
      JScrollPane jspB = new JScrollPane (jtaB);
  
      JTextArea jtaC = new JTextArea ();
      JScrollPane jspC = new JScrollPane (jtaC);
  
      JTextArea jtaD = new JTextArea ();
      JScrollPane jspD = new JScrollPane (jtaD);
  
      jsppA = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, treeView, jspA);
      jsppB = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, jsppA   , jspB);
      jsppC = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, jsppB   , jspC);
      jsppD = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, jsppC   , jspD);
  
      setTitle ("JTree example 2 - ND");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
      add (jsppD, BorderLayout.CENTER);
  
      jtaA.setText ("--- Post Order:");
      for (Enumeration <DefaultMutableTreeNode> e = root.postorderEnumeration(); e.hasMoreElements();) {
         DefaultMutableTreeNode d = e.nextElement();
         jtaA.append (String.format ("Node: %" + (1+d.getLevel()*3) + "s - %s\n", "", d.toString()));
      } // end printing tree
  
      jtaB.setText ("--- breadthFirstEnumeration Order:");
      for (Enumeration <DefaultMutableTreeNode> e = root.breadthFirstEnumeration(); e.hasMoreElements();) {
         DefaultMutableTreeNode d = e.nextElement();
         jtaB.append (String.format ("Node: %" + (1+d.getLevel()*3) + "s - %s\n", "", d.toString()));
      } // end printing tree
  
      jtaC.setText ("--- depthFirstEnumeration Order:");
      for (Enumeration <DefaultMutableTreeNode> e = root.depthFirstEnumeration(); e.hasMoreElements();) {
         DefaultMutableTreeNode d = e.nextElement();
         jtaC.append (String.format ("Node: %" + (1+d.getLevel()*3) + "s - %s\n", "", d.toString()));
      } // end printing tree
  
      jtaD.setText ("--- preorderEnumeration Order:");
      for (Enumeration <DefaultMutableTreeNode> e = root.preorderEnumeration(); e.hasMoreElements();) {
         DefaultMutableTreeNode d = e.nextElement();
         jtaD.append (String.format ("Node: %" + (1+d.getLevel()*3) + "s - %s\n", "", d.toString()));
      } // end printing tree
  
      pack ();
   //             setSize (1000, 500);
   //             resizeMe ();
   //             validate ();
      setLocationRelativeTo (null);
      setVisible (true);
  
      addComponentListener (
               new ComponentAdapter () {
                  public void componentResized (ComponentEvent e) {resizeMe();}
                  public void componentShown   (ComponentEvent e) {resizeMe();}
               });
   } // end constructor

   void resizeMe () {
      int n = paneCount;
      jsppD.setDividerLocation (1.0 - 1.0 / n--);
      jsppC.setDividerLocation (1.0 - 1.0 / n--);
      jsppB.setDividerLocation (1.0 - 1.0 / n--);
      jsppA.setDividerLocation (1.0 - 1.0 / n--);
   } // end resizeMe method

   DefaultMutableTreeNode createNodes () {
      DefaultMutableTreeNode t, u, v, w, x, y, z;
  
      z = new DefaultMutableTreeNode (new Element ("zero"      ));
      z.add       (t = new DefaultMutableTreeNode (new Element ("one A"     )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoA A"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoA B"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoA C"    )));
      u.add   (w = new DefaultMutableTreeNode (new Element ("threeAC A" )));
      u.add   (w = new DefaultMutableTreeNode (new Element ("threeAC B" )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoA D"    )));
      z.add       (t = new DefaultMutableTreeNode (new Element ("one B"     )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoB A"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoB B"    )));
      u.add   (w = new DefaultMutableTreeNode (new Element ("threeBB A" )));   
      u.add   (w = new DefaultMutableTreeNode (new Element ("threeBB B" )));
      w.add (x = new DefaultMutableTreeNode (new Element ("threeBBB A")));
      w.add (x = new DefaultMutableTreeNode (new Element ("threeBBB B")));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoB C"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoB D"    )));
      z.add       (t = new DefaultMutableTreeNode (new Element ("one C"     )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoC A"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoC B"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoC C"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoC D"    )));
      z.add       (t = new DefaultMutableTreeNode (new Element ("one D"     )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoD A"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoD B"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoD C"    )));
      t.add     (u = new DefaultMutableTreeNode (new Element ("twoD D"    )));
      return z;
   } // end createDataTree
} // end class JTreeExample

class Element {
   String data;

   public Element (String s) {
     data = s;
  
}

   public String toString () {
      return data;
  
}
} // end Node


ND.