35. JavaServer Pages

 
[Page 1073]

31.9. TreeModel and DefaultTreeModel

The TreeModel interface represents the entire tree. Unlike ListModel or TableModel , TreeModel does not directly store or manage tree data. TreeModel contains the structural information about the tree, and tree data is stored and managed by TreeNode .

DefaultTreeModel is a concrete implementation for TreeModel that uses TreeNode s. Figure 31.20 shows TreeModel and DefaultTreeModel .

Figure 31.20. TreeModel represents an entire tree.

Once a tree is created, you can obtain its tree model using the getModel method. Listing 31.12 gives an example that traverses all the nodes in a tree using the tree model. Line 3 creates a tree using JTree 's no-arg constructor with the default sample nodes, as shown in Figure 31.16. The tree model for the tree is obtained in line 4. Line 5 invokes the traversal method to traverse the nodes in the tree.

Listing 31.12. TestTreeModel.java
(This item is displayed on pages 1073 - 1074 in the print version)
 1   public class   TestTreeModel { 2   public static void   main(String[] args) { 3  javax.swing.JTree jTree1 =   new   javax.swing.JTree();  4  javax.swing.tree.TreeModel model = jTree1.getModel();  5  traversal(model, model.getRoot());  6 } 

[Page 1074]
 7 8   private static void   traversal 9 (javax.swing.tree.TreeModel model, Object root) { 10 System.out.print(root +   " "   ); 11   if   (  model.isLeaf(root)  )   return   ; 12   for   (   int   i =     ; i <  model.getChildCount(model.getRoot()  ); i++) { 13  traversal(model, model.getChild(root, i));  14 } 15 } 16 } 

The traversal method starts from the root of the tree. The root is obtained by invoking the getRoot method (line 5). If the root is a leaf, the method returns (line 11). Otherwise, it recursively invokes the traversal method to start from the children of the root (line 13). The output of the program is

 JTree colors blue violet red sports basketball soccer football food hot dogs pizza ravioli 

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net