Monday, February 16, 2009

Extending TreeItemRenderer in Flex 3

Hat tip to Mac Martine for his post on how to do this in Flex 2.
Tried posting to his blog with my improvements for Flex 3. Alas, 500 server error.

===
package
{
import mx.controls.Image;
import mx.controls.Tree;
import mx.controls.treeClasses.*;

public class MyTreeItemRenderer extends TreeItemRenderer
{
// myImage: holds the image we are adding to the tree nodes
protected var myImage:Image;

// set image properties
private var imageWidth:Number = 30;
private var imageHeight:Number = 20;

// the image to be placed in branch nodes
private var branchImage:String = "data/branch.gif";
private var leafImage:String = "data/leaf.gif";


public function MyTreeItemRenderer()
{
super();
}

override protected function createChildren():void
{
// create a new image() to hold the image we'll add to the tree item
myImage = new Image();

myImage.width = imageWidth;
myImage.height = imageHeight;
myImage.setStyle( "verticalAlign", "middle" );

// and apply it to the tree item
addChild(myImage);

super.createChildren();
}

override public function set data(value:Object):void
{
super.data = value;

// get the tree that owns us
var _tree:Tree = Tree(this.parent.parent);

// if the current node is a branch node
if(TreeListData(super.listData).hasChildren)
{
// we don't want to show the default branch icons, let's empty them
_tree.setStyle("folderClosedIcon", null);
_tree.setStyle("folderOpenIcon", null);
}
else
{
// if we are in here, then the current node is a leaf node
// we don't want to show the default leaf icons, let's empty them
_tree.setStyle("defaultLeafIcon", null);
}
}

override protected function updateDisplayList(unscaledWidth:Number,
unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if(super.data)
{
// if the current node is a branch
if(TreeListData(super.listData).hasChildren)
{
// get the current node and it's children as XMLList
//var currentNodeXMLList:XMLList = new XMLList(TreeListData(super.listData).item);

// get the number of children under the current node
//var numOfImmediateChildren:int = currentNodeXMLList[0].children().length();

// set the image to be displayed in the branches
myImage.source = branchImage;

// set the label text
// super.label.text = TreeListData(super.listData).label.text + "(" + numOfImmediateChildren + ")";

} else {
// if we are in here, then the current node is a leaf node
myImage.source = leafImage;
}
// reset the position of the image to be before the label
myImage.x = super.label.x;

// reset the position of the label to be after the image, plus give it a margin
super.label.x = myImage.x + imageWidth;
}
}
}
}