Monday, February 23, 2009

Using StringUtil Class in Flash

Using Flex ActionScript 3.0 classes in Flash is now easier than ever before due to the new addition of the Flash Library path and external library path.
Am going to demonstrate how users can use StringUtil class without the need to go through the hoops to make it work in Flash.


1. Launch Flex Builder.
2. Create "Flex Library Project" and call it "FlexUtilFlash".
3. Right Click on the "src" folder and create "ActionScript Class" and call it "FlexUtilFlash.as".
4. Copy and paste the following code to the class

package
{
import mx.utils.StringUtil;

public class FlexUtilFlash
{
public function FlexUtilFlash()
{
new StringUtil();
}

}
}

In the above class all what am doing is instantiating StringUtil class and include it into my SWC that am going to use in Flash.

5. Save.

Note : FlexUtilFlash.swc file automatically created and saved in the bin directory of the project file after saving the FlexUtilFlash.as file as below :



6. Launch Flash CS4 Professional.
7. Choose File > New > Flash File (ActionScript 3.0).
8. Choose File > Save and name the file FlashFlexUtil.fla. The location of the saved Flash file is unimportant, so you can save it in any folder you like.
9. Choose File > Publish Settings to access the Publish Settings dialog box.
10. Click the Flash tab to see the Flash Player and ActionScript settings.
11. Click the Settings button next to the ActionScript drop-down menu.
12. Click the Library Path tab.
13. Click the red SWC icon and browse to select the SWC file named FlexUtilFlash.swc that was generated by Flex in Step 5. After you select the FlexUtilFlash.swc file, the path to the file is added to the Library path window as below :



14. Open the Actions panel by choosing Window > Actions. Since the FlashFlexUtil.fla file contains only one layer, Frame 1 of Layer 1 is automatically selected. Copy and paste the following code into the Script window to instantiate an object of FlashFlexUtil:

import mx.utils.StringUtil;
var str:String = " This is Awesome!!!";
trace(str);
var sttTrim:String = StringUtil.trim(str);
trace(sttTrim);
15.Test Movie and you should see the result should be as below :





As you see above, adding the SWC allow you to use all the StringUtil class methods and properties in Flash.