Thursday, May 3, 2012

ADF: Tree using managed bean


For creating ADF tree component using managed bean:
  • Create a object representing tree item & this will have references to its children.
public class TreeNode {
    public TreeNode() {
        super();
    }    
    public TreeNode(int id, String name){
        this.id = id;
        this.name = name;
    }
    
    private int id;
    private String name;
    private List<TreeNode> childNodes;

    ...with getters & setters...
}
  • Create and Populate objects representing tree item with data, i did that in constructor of managed bean. Managed bean can be registered in either adfc-config.xml or faces-config.xml.
    public TreeBackingBean() {
        rootNode = new TreeNode(1, "World");
        TreeNode node2 = new TreeNode(2, "USA");
        TreeNode node3 = new TreeNode(3, "India");
        TreeNode node4 = new TreeNode(4, "Los Angeles");
        TreeNode node5 = new TreeNode(5, "Delhi");
        TreeNode node6 = new TreeNode(6, "Mumbai");
        
        List<TreeNode> l1 = new ArrayList<TreeNode>();
        l1.add(node2);
        l1.add(node3);
        rootNode.setChildNodes(l1);
        
        List<TreeNode> l2 = new ArrayList<TreeNode>();
        l2.add(node4);
        node2.setChildNodes(l2);
        
        List<TreeNode> l3 = new ArrayList<TreeNode>();
        l3.add(node5);
        l3.add(node6);
        node3.setChildNodes(l3);
    }
  • Use following API to create TreeModel:
org.apache.myfaces.trinidad.model.TreeModel treeModel = 
new org.apache.myfaces.trinidad.model.ChildPropertyTreeModel(objectOfNodeTreeItem, "childNodes");
Note: The second argument is String matching the property of objectOfTreeItem representing references to its children. If the name is mismatched, you will end up with "javax.el.PropertyNotFoundException" error.

  • Bind the value of <af:tree> from page to above "treeModel" instance. Final result be like:
The sample application can be downloaded from https://rapidshare.com/files/4090558697/TreeFromBeanExample.zip

1 comment:

  1. thanks for this example can you reupload the sample again

    ReplyDelete