Archive for the ‘actionscript’ Category

Selectable Text in Flex DataGridColumn

May 24, 2013

Last day my junior asked me a question “How do I make text selectable in a DataGridColumn? I want the user to copy the text from the datagrid.”. Well I had really didn’t thought about that feature till then. Important thing, by default you cannot copy the text shown in the datagrid if you are using the default ItemRenderer. But this turned out to be very very easy one. Couple of options.

1. Β The most simple one. Make the ItemRenderer of the datagrid column as mx.controls.Text.

<mx:DataGridColumn dataField="name" headerText="Name" itemRenderer="mx.controls.Text"/>

2. By default the item renderer of a datagrid column is DataGridItemRenderer which is based on TextField. And the selectable property is set to false. So extend another class from DataGridItemRenderer and set the selectable property to true.

package com.renderers
    import mx.controls.dataGridClasses.DataGridItemRenderer;

    public class SelectableDataGridItemRenderer extends DataGridItemRenderer
        public function SelectableDataGridItemRenderer()
            this.selectable = true;
<mx:DataGridColumn dataField="name" headerText="Name" itemRenderer="com.renderers.SelectableDataGridItemRenderer"/>

3. Create a custom component with a selectable label and assign it as the ItemRenderer.


<mx:Label xmlns:mx="" selectable="true">


<mx:DataGridColumn dataField="name" headerText="Name" itemRenderer="SelectableDataGridItemRenderer"/>

The last two options are just said, in case the first simple one doesn’t work. If you are using a custom Item Renderer, then you are on your own. πŸ™‚

Happy Coding Guys… πŸ™‚


Send Image to Flex from Java using HTTPService

September 19, 2012

I was doing some technology upgradation myself nowadays. As part of that I was writing my own twitter client, using Servlets as backend and Flex as Frontend. I used Twitter4J for twitter connectivity from Java, and I deployed the application in Jelastic, the rock solid cloud java server. Twitter connectivity, login process, retrieval, posting and retweeting was done and my app was very well working in beta stage. As my next improvement I tried to show up the user profile images. Twitter4J provides you with the profile image url and my task was to read the image and send the image across the network to the flex client. I could easily give the url of the image to the flex image control, but I felt doing like this.

Since I am using servlets, I use HTTPService to get connect to Java. Hence my main task was to send image through XML! What the heck, that was the first question that came to my mind. So I split my task into different steps :

1. Read the image from the URL in Java
2. Convert this into some sort of textual form
3. Send this across to Flex
4. Convert the textual form Image into something so that Flex Image control can render.

Lets go step-by-step.

1.Read the image from the URL in Java

I am 100% sure that there will be different way to read the image than how I did below. But this also do the trick. It just opens the stream of the url Object of type and reads byte chunks and put into a ByteArrayOutputStream.

URL url = "";
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096];
int n;

while ((n = > 0 ) {
bais.write(byteChunk, 0, n);
}catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
finally {
if (is != null) { is.close(); }

2. Convert this into some sort of textual form

Our next task is to change this read ByteArrayOutputStream into some textual form so that we can send it through XML. The best and most popular way to do this is to encode it using Base64. There are lots of Base64 encoding and decoding libraries available in the java market, from Oracle, Apache and all. I decided to use the one provided by Oracle themselves. The encoder returns you the binary object in the String format. Hence I wrote an util method for encoding the image from URL and it become like this.


import sun.misc.BASE64Encoder;

* @author Anoop Nair
public class UtilClass {

public static String base64Encode(URL url) throws Exception{
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096];
int n;

while ((n = > 0 ) {
bais.write(byteChunk, 0, n);
}catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
finally {
if (is != null) { is.close(); }
BASE64Encoder encoder = new BASE64Encoder();
String encodedImage = encoder.encode(bais.toByteArray());
return encodedImage;

3. Send this across to Flex

Do I need to say anything about this. Embed this encoded string into an XML and use your HTTPService and its result handler and fault handler to transmit this XML to flex. πŸ™‚ I am becoming lazy here. He He.

4. Render this image in Flex

Thanks to those tons of developers out there who are doing hard-core library development. Bingo, Flex also have a built-in Base64Encoder and Base64Decoder. πŸ™‚Β  Similar to Java I wrote a Util function in Flex and used the decoder to decode the image and convert it into byte array.


import flash.utils.ByteArray;
import mx.utils.Base64Decoder;

public class UtilClass {
private static var base64Dec:Base64Decoder;

public static function base64Decode(encodedString:String):ByteArray{
var byteArr:ByteArray;

base64Dec = new Base64Decoder();
byteArr = base64Dec.toByteArray();
return byteArr;

This byte array can be loaded and bound into the image control like this, where the ByteArray is stored under the variable userImage :


Or this can also be done using actionscript like this :


That’s it guys. It was damn easy, right? But if you wanna be a good developer or programmer, go and read more about Base64 encoding and its algorithm, or try to implement your own encoder. The Apache team is really making us lazy, aren’t they? πŸ˜› That’s it guys, Cheers, Happy Coding πŸ™‚

Set cursor position in the Flex Text Controls

September 19, 2012

You have a text control in flex. At some random event, you need to focus the text control. Simple, right. Just give :


All is fine. So what if you need to add some text to the text control? Like the following :

txtInput.text = “@anoop_pk”;

This will definitely bring the focus on the control. But hold on. The cursor will be blinking on the beginning of the text and you want it to set to the end of the text. Okay it is quite simple. Flex framework provides with method setSelection for the text controls. Which can be used to select a part of the text in the text controls programatically. The typical usage is like this :


We can use this to achieve our task by giving like this :

txtInput.setSelection(txtInput.text.length, txtInput.text.length);

We are infact selecting nothing, but this will force the cursor to move to the end of the text. Thats it guys, a small tip to keep my writing active. Lots of work. See you. Happy Coding. πŸ™‚

Show a default prompt in Flex Combobox

May 8, 2012

At times, you may need to show a combobox, where none of the items should be selected by default and it should show something like ‘Please Select’. One way is to add this object also to the dataprovider, as the first item. But if you think that is a burden for your dataprovider, then Flex SDK provides you a built in option. To be frank, after working in Flex for more than 4 years, I am finding out this now only. πŸ™‚ You can use the prompt property of the combobox to show a default value. This will go away once you select one option, and you cannot bring it back. (I think so, but there are high chances that this is not true).

eg :

<mx:ComboBox id=”comboBox”Β  dataProvider=”{dataprovider}”
labelField=”name” prompt=”Please select an entry” />

That’s all guys. Flex Your Life. Cheers. πŸ™‚

Calling Flex / Actionscript functions from Javascript

May 8, 2012

Nowadays I am working with Flex projects, that runs on Lotus Notes platform, which consumes data from Lotus Notes backend. Since there is no remote services like BlazeDS to connect to Notes server, am now greatly dependant on HTTPService and Javascript. Calling a javascript function from Flex is quite easy. Just use the ExternalInterface API. For those who don’t know the way, this is how it is getting called.

In AS3

if(ExternalInterface.available){“openNotes”, parameter);

In Javascript

function openNotes(notesUrl){, ”, ‘width=1000,height=600’);

It is quite easy. But what if you need to call the reverse. ie, calling actionscript function from javascript. We can use the same ExternalInterface api for achieve this. There is a method called addCallback, available in ExternalInterface. addCallback method registers an ActionScript method as callable from the container. After a successful invocation of addCallBack(), the registered function in the player can be called by JavaScript or ActiveX code in the container. The first parameter is the name by which the container can invoke the function and the second parameter is the function closure to invoke. Below is the step-by-step configuration:

Step 1 : Register the call back from actionscript. For eg, call the below method in the creationComplete or initialize event of the component.

private function createCallBack(event:Event):void{
ExternalInterface.addCallback(“updateNotes”, getNotes);

private function getNotes():void{
//do whatever you want after getting the hold

Step 2 : Create logic in javascript to invoke the AS3 function.

function updateFlex(){

The appName is the name and id of the embedded swf object in the HTML. Like below :

That’s it. Now you can call the updateFlex javascript method from your HTML and it will invoke the AS3 callback function. Enjoy Coding guys. Flex Your Life. Cheers. πŸ™‚

Flex / AS3 – Remove all children of a container

May 8, 2012

I know this is not that big thing. But still wanna scribble it down. In order to remove all the children of the container, there is no set function available. You can write a generic method, may be a static method and call that. The logic is to iterate over all the available children and remove one by one. Something like this :

static public function removeAllChildren(parent:UIComponent):void{
while(parent.numChildren > 0 ){
parent.removeChildAt( 0 );

The parent can be either UIComponent or its subclass. The best practice would be to write this method in your component itself, so that this method will become a part of the component. Then you can write something like this :

public function removeAllChildren():void{
while(numChildren > 0 ){
removeChildAt( 0 );

That’s all guys, Happy Coding. πŸ™‚

Check if an XML node or attribute exists in E4X format

April 25, 2012

E4X is the heaven when it comes to XML parsing. Since flex natively supports E4X format results, it makes our lives very easy. But there are lots of tips and tricks to play in E4X parsing.

Suppose you have an optional XML node and you need to check whether it exists in the XML. Obviously our actionscript and javascript memories will ask us to try this way if(xml.node != null) or if(xml.node). But if you try this, it is not gonna work. It will probably give you unwanted result or if your day is going too good you will get a reference error. The below are some ways you can try out :

For checking Nodes :

if(xml.someNode.length() > 0){ // Node exists }if(xml.someNode != undefined)
{ // Node exists }

For checking Attributes:

if(xml.@someAttr.length() > 0)
{ // Attribute exists }

if(xml.@someAttr != undefined)
{ // Attribute exists }

That’s it guys. Happy Coding! πŸ™‚ Flex your life.

Why MVC? Simply Explained

March 29, 2012

Disclaimer : I collected this from one support forum. Its not my original post.

MVC (Model – View – Controller) is one of those concepts that only starts to make sense when you’re dealing with larger applications and/or when working on the same application with several developers.

Compare it with tasks, if you’ve got 3 tasks that need to be done on a certain date, you won’t feel the need to have some kind of task organization, but if you have to deal with dozens of different tasks, with various due dates you’ll start using todo-lists. Then when you start working with a team of people and you need to prioritize and sequence tasks, you realize simple todo-lists won’t suffice and you’ll end up with applying SCRUM for instance (it obviously deals with more than task management, but it is one of the core parts of the methodology)

The same applies to MVC. It’s benefits are absolutely not restricted to large-scale, team-based development, but they become most obvious in such situations.

Let’s say you need to make a web application that loads some data in a xml file, lets the user do some operations on that data and saves the users edits in a SharedObject.
Fine. It’s a small application, you can develop it pretty fast and there’s no need to start thinking about using MVC or other patterns for structuring your components (not talking about UI components here, just cogs in the machine).
The application is a huge success and your client is extremely satisfied, they ask you to change the application because they’ll be setting up a back end with which the xml file can be manipulated by them, in fact no, they want to use a database instead of the file. And since it’s 2012 they definitely need an iphone app as well.
You’ll start working on the web application and since the deadline’s not just tight, but completely insane chances are you’ll be modifying it to reflect the use case changes, make a copy of the entire project to create the iphone app and again simply making the iOS required changes in that project directly.
Now repeat this five times. The client keeps on asking modifications. expansions etc. These can be UI related changes, but even complete backend architecture swaps, going from REST to SOAP for instance.
If you didn’t structure your project using MVC, you’ll be in a world of pain. No, you’ll be in a world of pain anyway, but had you used MVC from the start you’d notice that some things would’ve been less painful:

  • 95% of the code for the web application and the iphone app will be the same, but instead of saving the user data to a Shared Object or through a web service, you’d be using a local DB for instance. Due to the separation of concerns as promoted with MVC (and even more specifically with RL) you’d notice that the only thing different in the web app and the iphone app would’ve been a single service class. Without MVC chances are pretty high you’ll be making modifications in a bunch of classes.
  • The same applies to the UI for instance. Again, the heart of the application is the same, only the way it’s presented to the user is different. Due to separation of your app into the various tiers you’ll notice that changing the UI for the iphone app, will only have an impact on view classes and you’ll spent a tremendous amount of time less of searching through your code and finding out where to change what.
  • w/o MVC 95% of both apps would still be the same, but the differences would’ve been scattered in various files, here and there some lines, with MVC the differences will be in using different classes, ie the changes are more compact and overseeable.

All in all using MVC makes your code more structured and far more flexible to accomodate change in size, platform etc. etc.

Courtsey : creynders of Robotlegs Support

Datatype serialization from Java to Actionscript

February 24, 2012

Chances are there that we might mistake the datatype, when it gets serialized from Java objects to AS3 objects. The table below shows the java datatype and its corresponding AS3 datatype. This is an excerpt from the live docs.

Java type ActionScript type (AMF 3)
enum (JDK 1.5) String
java.lang.String String
java.lang.Boolean, boolean Boolean
java.lang.Integer, int intIf value < 0xF0000000 || value > 0x0FFFFFFF, the value is promoted to Number due to AMF encoding requirements.
java.lang.Short, short intIf i < 0xF0000000 || i > 0x0FFFFFFF, the value is promoted to Number.
java.lang.Byte, byte[] intIf i < 0xF0000000 || i > 0x0FFFFFFF, the value is promoted to Number.
java.lang.Byte[] flash.utils.ByteArray
java.lang.Double, double Number
java.lang.Long, long Number
java.lang.Float, float Number
java.lang.Character, char String
java.lang.Character[], char[] String
java. math.BigInteger String
java.math.BigDecimal String
java.util.Calendar DateDates are sent in the Coordinated Universal Time (UTC) time zone. Clients and servers must adjust time accordingly for time zones.
java.util.Date DateDates are sent in the UTC time zone. Clients and servers must adjust time accordingly for time zones.
java.util.Collection (for example, java.util.ArrayList) mx.collections.ArrayCollection
java.lang.Object[] Array
java.util.Map Object (untyped). For example, a java.util.Map[] is converted to an Array (of Objects).
java.util.Dictionary Object (untyped)
org.w3c.dom.Document XML object
null null
java.lang.Object (other than previously listed types) Typed ObjectObjects are serialized using Java bean introspection rules and also include public fields. Fields that are static, transient, or nonpublic, as well as bean properties that are nonpublic or static, are excluded.

That’s it guys. Happy Coding. πŸ™‚

Adding Glow to a Shape in AS3

January 12, 2012

Adding a glow to a programatically drawn shape is very easy in actionscript. We just need to create the GlowFilter object and apply it to the filters property. A quick example is follows

var whiteGlow:GlowFilter = new GlowFilter(0xFFFFFF, 0.8, 30, 30, 1, 1, false, false);

var sp:Sprite = new Sprite();
sp.filters = [whiteGlow];

That’s it. Similary you can add other filters such as GradientFilter, BlurFilter, etc. For a detail list of the available display filters refer the livedocs : Available Display Filters.

Happy Coding guys. πŸ™‚

%d bloggers like this: