The TreeModel Class
The com.mycompany.jsf.model.TreeModel
class
is
the model class for the tree component. It provides random access to
nodes in a tree made up of instances of the
TreeNode
class we looked at in Chapter 12:
package com.mycompany.jsf.model; import java.util.StringTokenizer; import javax.faces.component.NamingContainer; public class TreeModel { private final static String SEPARATOR = String.valueOf(NamingContainer.SEPARATOR_CHAR); private TreeNode root; private TreeNode currentNode; public TreeModel(TreeNode root) { this.root = root; } public TreeNode getNode( ) { return currentNode; } public void setNodeId(String nodeId) { if (nodeId == null) { currentNode = null; return; } TreeNode node = root; StringBuffer sb = new StringBuffer( ); StringTokenizer st = new StringTokenizer(nodeId, SEPARATOR); sb.append(st.nextToken( )).append(SEPARATOR); while (st.hasMoreTokens( )) { int nodeIndex = Integer.parseInt(st.nextToken( )); sb.append(nodeIndex); try { node = (TreeNode) node.getChildren( ).get(nodeIndex); } catch (IndexOutOfBoundsException e) { String msg = "Node node with ID " + sb.toString( ) + ". Failed to parse " + nodeId; throw new IllegalArgumentException(msg); } sb.append(SEPARATOR); } currentNode = node; } }
The TreeModel
constructor takes the root
TreeNode
reference as its single argument and
saves it in an instance variable. The setNodeId()
method sets the current node to the specified node ID, which is a colon-separated list of node indexes. For instance, “0:0:1” ...
Get JavaServer Faces now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.