Saturday, January 8, 2011

AS3 DataGrid component: Part 5

In this tutorial we will learn how to change text align of a cell using CellRenderers.

This is what we're going to make:


CellRenderer is a class that renders cells of data grids. The class is built-in, but we can extend it and create our own cell renderer and then apply it to a collumn. Find the line where you create the job column in your code and add this:

col_job.cellRenderer = jobCellRenderer;

jobCellRenderer is a class we're going to create. Make a new as3 file, call it jobCellRenderer.as and put it in the same directory with your fla file.

Here's the class:

package 
{

import fl.controls.listClasses.CellRenderer;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;

public class jobCellRenderer extends CellRenderer
{
private var tf:TextFormat;

public function jobCellRenderer()
{
tf = new TextFormat();
tf.align = TextFormatAlign.CENTER;
}

override protected function drawLayout():void
{
textField.setTextFormat(tf);
super.drawLayout();
}
}
}

Now let's break it into parts to understand it better:

import fl.controls.listClasses.CellRenderer;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;

Here we import all the necessary classes. In this example I'm just going to change the text align of all the cells in this column.

public class jobCellRenderer extends CellRenderer

This way we create the class based on the CellRenderer class.

public function jobCellRenderer()
{
tf = new TextFormat();
tf.align = TextFormatAlign.CENTER;
}

Here we simply create the text format object we will later apply to the text.

override protected function drawLayout():void
{
textField.setTextFormat(tf);
super.drawLayout();
}

And this is the function that actually renders the cells. It already exists, so we override it and add the stuff we want - in this case, we apply the textField's format to our tf object.

If you don't want to limit the renderer just to one column, you can apply it to the whole datagrid (except the header):

myGrid.setStyle("cellRenderer", jobCellRenderer);

Thanks for reading!

Related:

AS3 DataGrid component: Part 1
AS3 DataGrid component: Part 2
AS3 DataGrid component: Part 3
AS3 DataGrid component: Part 4
AS3 DataGrid component: Part 6
AS3 DataGrid component: Part 7
AS3 DataGrid component: Part 8
AS3 DataGrid component: Part 9
AS3 DataGrid component: Part 10
AS3 DataGrid component: Part 11
AS3 DataGrid component: Part 12
AS3 DataGrid component: Part 13
AS3 DataGrid component: Part 14
AS3 DataGrid component: Part 15
AS3 DataGrid component: Part 16

No comments:

Post a Comment