November 23, 2009

Custom indeterminate Preloader in Actionscript3 in Flex

Hi,
The custom inderterminate preloader can be build by actionscript only and it can be support for change the background and preloader color by set the style of the custom preloader class. The code as follows


package com
{
import mx.controls.Label;
import mx.containers.VBox;
import mx.controls.ProgressBar;
import mx.managers.PopUpManager;
import flash.display.DisplayObjectContainer;
[Style(name="mapLoaderBackgroundColor",type="uint",format="Color",inherit="no")]
[Style(name="maploaderProgressColor",type="uint",format="Color",inherit="no")]
public class MapPreloader extends VBox
{
private var _progressBar:ProgressBar;
private var _loadingLabel:Label;
public function MapPreloader()
{
super();
width = 250;
height = 80;
setStyle("paddingTop",20);
setStyle("paddingBottom",10);
setStyle("cornerRadius",10);
setStyle("backgroundAlpha",1);
setStyle("borderStyle","solid");
setStyle("horizontalAlign","center");
setStyle("verticalScrollPolicy","off");
setStyle("horizontalScrollPolicy","off");
}
override protected function createChildren():void
{
super.createChildren();
_progressBar = new ProgressBar();
_progressBar.label = "";
_progressBar.labelPlacement = "center";
_progressBar.width = 200;
_progressBar.indeterminate = true;
_progressBar.setStyle("themeColor",0x333333);
addChild(_progressBar);
_loadingLabel = new Label();
_loadingLabel.text = "Loading...";
_loadingLabel.percentWidth = 100;
_loadingLabel.setStyle("fontSize",12);
_loadingLabel.setStyle("textAlign","center");
addChild(_loadingLabel);
}
public function show(parent:DisplayObjectContainer):void
{
PopUpManager.addPopUp(this,DisplayObjectContainer(parent),true);
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth,unscaledHeight);
var _bgColor:uint = getStyle("mapLoaderBackgroundColor");
setStyle("backgroundColor",_bgColor);
var _progressColor:uint = getStyle("maploaderProgressColor");
_progressBar.setStyle("themeColor",_progressColor);
}
}
}

The color of custom indeterminate preloader can be change by following way

MapPreloader{
mapLoaderBackgroundColor:#FF0000;
maploaderProgressColor:#FFCC00;
}

Send SMS to Mobile using Way2SMS webservice in Adobe Air

Hi,
I created one appication for send sms to mobile phones all over india. I use the way2sms service provider for send the message to mobile phone. Here i mention the code for send sms message to mobile phones.

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" backgroundColor="0xFFFFFF" width="500" height="380" showStatusBar="false"
layout="vertical" verticalGap="4" verticalScrollPolicy="off" horizontalScrollPolicy="off" creationComplete="onInit()" showTitleBar="false"
>
<mx:Script>
<![CDATA[
import mx.events.CloseEvent;
import mx.controls.Alert;
import flash.net.navigateToURL;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.events.ValidationResultEvent;
private var _dockImage:BitmapData;
private function onInit():void
{
var _loader:Loader = new Loader();
_loader.load(new URLRequest("images/systray_icon_16.png"));
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImageLoaded);
}
private function onImageLoaded(evt:Event):void
{
_dockImage = evt.target.content.bitmapData;
}
private function onCloseApp(evt:Event):void
{
NativeApplication.nativeApplication.icon.bitmaps = [_dockImage];
}
public function onResponse(e:ResultEvent):void
{
if(e.result == "invalid login")
txt_status.text = e.result.toString();
else if(e.result == "done")
txt_status.text = "Message was send successfully";
else
txt_status.text = e.result.toString();
}
public function onFault(e:FaultEvent):void
{
txt_status.text = "Message was not send";
}
private function sendMsg():void
{
WS.getOperation('sendSMSToMany').send();
}
private function redirectPage():void
{
navigateToURL(new URLRequest("http://wwwa.way2sms.com/jsp/UserRegistration.jsp"),"_POST");
}
]]>
</mx:Script>
<mx:WebService id="WS" wsdl="http://www.aswinanand.com/sendsms.php?wsdl" showBusyCursor="true">
<mx:operation name="sendSMSToMany" result="onResponse(event)" fault="onFault(event)">
<mx:request>
<uid>
{txt_user.text}
</uid>
<pwd>
{txt_pwd.text}
</pwd>
<phone>
{txt_mobile.text}
</phone>
<msg>
{txt_msg.text}
</msg>
</mx:request>
</mx:operation>
</mx:WebService>
<mx:HBox verticalGap="1" horizontalGap="3" width="100%">
<mx:Image source="@Embed(source='images/logo.jpg')"/>
<mx:Text text="Send SMS to Friends in India" fontSize="18" fontWeight="bold"/>
</mx:HBox>
<mx:HBox verticalGap="1" width="100%" horizontalAlign="center">
<mx:Text id="txt_status" fontSize="16" fontWeight="bold" color="#FF0000"/>
</mx:HBox>
<mx:Form verticalGap="8" y="-30">
<mx:FormItem label="Username:" fontSize="14" color="#0000FF" fontWeight="bold" width="98%">
<mx:TextInput id="txt_user" fontSize="12" color="0x000000" fontWeight="normal" width="150" maxChars="10" restrict="0-9"/>
</mx:FormItem>
<mx:FormItem label="Password:" fontSize="14" color="#0000FF" fontWeight="bold" width="98%">
<mx:TextInput id="txt_pwd" fontSize="12" color="0x000000" fontWeight="normal" width="150" displayAsPassword="true"/>
</mx:FormItem>
<mx:FormItem label="Mobile NO:" fontSize="14" color="#0000FF" fontWeight="bold" width="98%">
<mx:TextInput id="txt_mobile" fontSize="12" color="0x000000" fontWeight="normal" width="150" maxChars="10" restrict="0-9"/>
</mx:FormItem>
<mx:FormItem label="Type Message:" fontSize="14" color="#0000FF" fontWeight="bold" width="98%">
<mx:TextArea id="txt_msg" fontSize="12" color="0x000000" fontWeight="normal" width="180" height="80" maxChars="140"
change="maxchar.text = '* maxchar 140('+txt_msg.text.length.toString()+')'"/>
<mx:Label id="maxchar" text="* maxchar 140(0)" fontSize="11" color="0xFF0000" fontWeight="normal"/>
</mx:FormItem>
<mx:FormItem width="100%" paddingTop="10">
<mx:HBox width="100%">
<mx:Button label="Send" click="sendMsg()"/>
<mx:Button label="Register Now" click="redirectPage()"/>
</mx:HBox>
</mx:FormItem>
</mx:Form>
</mx:WindowedApplication>

Interact with PayPal in Flex3

Hi,
Here i post the nice example for choose the book from the list and enter the quantity of the book that they want. Then pass the information to the paypal application and we can see the amount of product that we order from the flex application. In below i given the code for that.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import flash.net.navigateToURL;
private var _cmbArr:Array;
private function onInit():void
{
var _urlRequest:URLRequest = new URLRequest("xmls/bookList.xml");
var _urlLoader:URLLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE,onXMLLoadComplete);
_urlLoader.load(_urlRequest);
}
private function onXMLLoadComplete(evt:Event):void
{
_cmbArr = new Array();
var _xml:XML = XML(evt.target.data);
var _xmlList:XMLList = XMLList(_xml.book);
_cmbArr.push("Select Product");
for(var i:int=0;i<_xmlList.length();i++)
{
_cmbArr.push({label:_xmlList[i].@name,id:_xmlList[i].@id,price:_xmlList[i].@price,tax:_xmlList[i].@tax,mail:_xmlList[i].@ordermail,thumb:_xmlList[i].@thumburl});
}
cmb_product.dataProvider = _cmbArr;
}
private function onProductChange(evt:Event):void
{
txt_prodid.text = cmb_product.selectedItem.id;
txt_amt.text = cmb_product.selectedItem.price;
txt_tax.text = cmb_product.selectedItem.tax;
img_src.source = cmb_product.selectedItem.thumb;
txt_desc.text = cmb_product.selectedItem.label;
}
private function makePayment():void
{
var url:String = "http://www.paypal.com/cgi-bin/webscr";
var _urlRequest:URLRequest = new URLRequest(url);
var _urlVar:URLVariables = new URLVariables();
_urlVar.cmd = "_xclick";
_urlVar.currency_code = "USD";
_urlVar.business = cmb_product.selectedItem.mail;
_urlVar.item_number = cmb_product.selectedItem.id;
_urlVar.item_name = cmb_product.selectedItem.label;
_urlVar.amount = cmb_product.selectedItem.price;
_urlVar.quantity = txt_qty.text;
_urlVar.tax = cmb_product.selectedItem.tax;
_urlRequest.data = _urlVar;
_urlRequest.method = URLRequestMethod.POST;
navigateToURL(_urlRequest,"_parent");
}
]]>
</mx:Script>
<mx:HBox paddingLeft="20" paddingTop="20">
<mx:Form backgroundColor="#FFFFFF" height="240">
<mx:Label width="100%" text="Product Catalogue" fontFamily="Arial" fontSize="15" fontWeight="bold" textAlign="center"/>
<mx:FormItem label="Choose Item :" fontFamily="Arial" fontSize="12">
<mx:ComboBox id="cmb_product" width="150" height="23" fontFamily="Arial" fontSize="12" change="onProductChange(event)"/>
</mx:FormItem>
<mx:FormItem label="Product ID :" fontFamily="Arial" fontSize="12">
<mx:TextInput id="txt_prodid" editable="false" width="150" height="23"/>
</mx:FormItem>
<mx:FormItem label="Amount :" fontFamily="Arial" fontSize="12">
<mx:TextInput id="txt_amt" editable="false" width="150" height="23"/>
</mx:FormItem>
<mx:FormItem label="Quantity :" fontFamily="Arial" fontSize="12">
<mx:TextInput id="txt_qty" text="1" width="150" height="23"/>
</mx:FormItem>
<mx:FormItem label="Tax :" fontFamily="Arial" fontSize="12">
<mx:TextInput id="txt_tax" editable="false" width="150" height="23"/>
</mx:FormItem>
<mx:FormItem>
<mx:Image source="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" width="60" maintainAspectRatio="true" horizontalCenter="0" verticalCenter="0" click="makePayment()"/>
</mx:FormItem>
</mx:Form>
<mx:VRule height="100%" strokeColor="#CCCCCC"/>
<mx:VBox height="240" backgroundColor="#666666">
<mx:Image id="img_src" width="250" height="200" verticalAlign="bottom" horizontalAlign="center"/>
<mx:Text id="txt_desc" fontFamily="Arial" fontSize="12" textAlign="center" fontWeight="bold" color="#FFFFFF" width="100%" height="20"/>
</mx:VBox>
</mx:HBox>
</mx:Application>

The sample xml file for accessing those above example as follows

<?xml version="1.0" encoding="UTF-8"?>
<BookList>
<book id="201" name="Cool 3D" price="250" tax="2" ordermail="order@macromedia.com" thumburl="assets/images/cool3d.jpg"/>
<book id="010" name="Dream Weaver" price="180" tax="4" ordermail="order@adobe.com" thumburl="assets/images/dreamweaver.gif"/>
<book id="001" name="Dream WeaverMX" price="300" tax="2" ordermail="order@adobe.com" thumburl="assets/images/dreamweavermx.gif"/>
<book id="413" name="Open Suse" price="280" tax="6" ordermail="order@sunsystems.com" thumburl="assets/images/opensuse.png"/>
<book id="271" name="Software Application" price="320" tax="4" ordermail="order@microsoft.com" thumburl="assets/images/swapp.jpg"/>
</BookList>

Rotate the Header Text in Datagrid in Flex3

Hi,
Here is the nice example for rotate the header text of the datagrid. The custom class i created for rotate the header text of Datagrid. When we need to rotate the text we must embed the text otherwise it cannot be visible the header text after rotate it.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" >
<mx:Style>
@font-face
{
src: url("/assets/fonts/trebucbd.ttf");
fontFamily: "TrebuchetMSBold";
fontWeight: bold;
}
</mx:Style>
<mx:Script>
<![CDATA[
import com.GridHeader;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.rpc.events.HeaderEvent;
import mx.controls.DataGrid;
[Bindable]
private var dp1:Array = [{Product: "ADBE", name: "Adobe Systems Inc.", price: 49.95},
{Product: "MACR", name: "Macromedia Inc.", price: 39.95},
{Product: "MSFT", name: "Microsoft Corp.", price: 25.95},
{Product: "IBM", name: "IBM Corp.", price: 42.55}];
[Bindable]
private var dp2:Array = [{Product: "SOFT", name: "Software", price: 49.95},
{Product: "HARD", name: "Hardware", price: 39.95},
{Product: "NETW", name: "Network", price: 25.95}];
private function onChangeProvider():void
{
if(dg.dataProvider.length == 4)
dg.dataProvider = dp2;
else if(dg.dataProvider.length == 3)
dg.dataProvider = dp1;
}
]]>
</mx:Script>
<mx:VBox>
<mx:DataGrid id="dg" dataProvider="{dp1}">
<mx:columns>
<mx:DataGridColumn headerText="Product" dataField="Product" headerRenderer="com.GridHeader"/>
<mx:DataGridColumn headerText="Name" dataField="name" headerRenderer="com.GridHeader"/>
<mx:DataGridColumn headerText="Price" dataField="price" headerRenderer="com.GridHeader"/>
</mx:columns>
</mx:DataGrid>
<mx:Button label="Change Provider" click="onChangeProvider()"/>
</mx:VBox>
</mx:Application>

The code for the custom class for rotate the text as follows

package com
{
import flash.text.AntiAliasType;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import mx.containers.VBox;
import mx.controls.listClasses.IListItemRenderer;
public class GridHeader extends VBox implements IListItemRenderer
{
private var _lbl:TextField;
public function GridHeader()
{
super();
height = 60;
setStyle("backgroundColor",0xFF0000);
setStyle("verticalGap",2);
}
override protected function createChildren():void
{
super.createChildren();
var _txtFormat:TextFormat = new TextFormat();
_txtFormat.font = "TrebuchetMSBold";
_txtFormat.size = 13;
_txtFormat.bold = true;
_txtFormat.color = 0x0000FF;
_txtFormat.align = "center";
_lbl = new TextField();
_lbl.autoSize = TextFieldAutoSize.LEFT;
_lbl.embedFonts = true;
_lbl.antiAliasType = AntiAliasType.ADVANCED;
_lbl.defaultTextFormat = _txtFormat;
_lbl.rotation = 270;
rawChildren.addChild(_lbl);
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
if(data.headerText != null data.headerText != "")
{
_lbl.text = data.headerText;
_lbl.y = height-5;
_lbl.x = (width - _lbl.width)/2;
}
}
}
}

September 03, 2009

Need 10 Explorer for Flex Developer

Hi,
The below 10 Explorer are necessary for concentrate on design of Flex application interface and for the new flex developer it will guide to work on flex platform and to become a good user interface design in Flex platform. The necesary 10 Explorer are as follows and use it and enjoy

01.Tour de Flex

Free transform tool using Rectangle class in Flex3

Hi,
I had seen lot of sites are using the already existing free transform tool and i found the bug on free transform tool component during resize but it cannot be restrict when mouse goes out of the stage area of the flash application. But based on the project that i am currently working as i need to restrict the resize of the component within the working area. Then i decided to develop a own free transform tool with the options as move and resize the component with eight corners. Finally i did and finish the concept of create the free transform tool and using the Rectangle class only used for manage the resize and move the free transform tool. This free transform tool move with in the boundary area and restrict the size into minimum size as well. The code for the free transform tool that i try out as below.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
//For Resize corner Tabs
private var _leftTopSprite:Sprite;
private var _leftMiddleSprite:Sprite;
private var _leftBottomSprite:Sprite;
private var _topMiddleSprite:Sprite;
private var _bottomMiddleSprite:Sprite;
private var _rightTopSprite:Sprite;
private var _rightMiddleSprite:Sprite;
private var _rightBottomSprite:Sprite;
//For variables declarations
private var _curTab:Sprite;
private var _sprite:Sprite;
private var _resizeWidth:Number;
private var _resizeHeight:Number;
private var _resizeStartX:Number;
private var _resizeStartY:Number;
private var _resizeHolder:Sprite;
private var _spriteHolder:Sprite;
private var _resizeRect:Rectangle;
private var _isResizeTab:Boolean = false;
private var _prevSprite:Sprite = null;
private var _currentSprite:Sprite = null;
private var _resizeInterface:UIComponent;
private static const HOTSPOT_MIN_SIZE:uint = 45;
private static const RESIZE_MAXIMUM_WIDTH:uint = 850;
private static const RESIZE_MAXIMUM_HEIGHT:uint = 550;
//For setup the Interface
private function onInit():void
{
_resizeInterface = new UIComponent();
_spriteHolder = new Sprite();
_spriteHolder.graphics.clear();
_spriteHolder.graphics.beginFill(0xFFFFFF,1);
_spriteHolder.graphics.drawRect(0,0,RESIZE_MAXIMUM_WIDTH,RESIZE_MAXIMUM_HEIGHT);
_spriteHolder.graphics.endFill();
_resizeInterface.addChild(_spriteHolder);
_sprite = drawSprite();
_sprite.name = "s1";
_spriteHolder.addChild(_sprite);
_sprite = drawSprite();
_sprite.name = "s2";
_spriteHolder.addChild(_sprite);
_sprite.x = 250;
_sprite.y = 50;
addChild(_resizeInterface);
_resizeInterface.x = 50;
_resizeInterface.y = 50;
}
private function drawSprite():Sprite
{
var _sp:Sprite = new Sprite();
_sp.graphics.clear();
_sp.graphics.beginFill(0xFF0000,0.8);
_sp.graphics.drawRect(0,0,200,200);
_sp.graphics.endFill();
_sp.cacheAsBitmap = false;
_sp.focusRect = false;
_sp.addEventListener(MouseEvent.MOUSE_DOWN,onSpriteDown);
addEventListener(MouseEvent.MOUSE_MOVE,onMoveSprite);
_sp.addEventListener(MouseEvent.MOUSE_UP,onStopSprite);
return _sp;
}
private function onSpriteDown(evt:MouseEvent):void
{
var _dragRect:Rectangle;
_prevSprite = _currentSprite;
var spr:Sprite = evt.target as Sprite;
_currentSprite = spr;
_resizeRect = spr.getBounds(spr.parent);
if(_prevSprite != null && _resizeHolder && _prevSprite.name != _currentSprite.name)
{
if(_resizeHolder)
{
_prevSprite.removeChild(_resizeHolder);
_isResizeTab = false;
_resizeHolder = null;
}
}
if(_prevSprite != null && _prevSprite.name == _currentSprite.name)
{
stage.focus = _currentSprite;
}
if(_resizeHolder == null && !_isResizeTab)
{
//For draw black line around selected sprite
_resizeHolder = new Sprite();
_resizeHolder.graphics.clear();
_resizeHolder.graphics.lineStyle(1,0x000000);
_resizeHolder.graphics.drawRect(0,0,_resizeRect.width,_resizeRect.height);
_resizeHolder.graphics.endFill();
_resizeHolder.cacheAsBitmap = false;
//Left side resize tab
_leftTopSprite = drawResizeTab();
_leftTopSprite.name = "LT";
_resizeHolder.addChild(_leftTopSprite);
_leftTopSprite.x = - 10;
_leftTopSprite.y = - 10;
_leftTopSprite.buttonMode = true;
_leftMiddleSprite = drawResizeTab();
_leftMiddleSprite.name = "LM";
_resizeHolder.addChild(_leftMiddleSprite);
_leftMiddleSprite.x = - 10;
_leftMiddleSprite.y = (_resizeRect.height - _leftMiddleSprite.height)/2;
_leftMiddleSprite.buttonMode = true;
_leftBottomSprite = drawResizeTab();
_leftBottomSprite.name = "LB";
_resizeHolder.addChild(_leftBottomSprite);
_leftBottomSprite.x = - 10;
_leftBottomSprite.y = _resizeRect.height - 10;
_leftBottomSprite.buttonMode = true;
//-----------------------
//Right side resize tab
_rightTopSprite = drawResizeTab();
_rightTopSprite.name = "RT";
_resizeHolder.addChild(_rightTopSprite);
_rightTopSprite.x = _resizeRect.width - 10;
_rightTopSprite.y = - 10;
_rightTopSprite.buttonMode = true;
_rightMiddleSprite = drawResizeTab();
_rightMiddleSprite.name = "RM";
_resizeHolder.addChild(_rightMiddleSprite);
_rightMiddleSprite.x = _resizeRect.width - 10;
_rightMiddleSprite.y = (_resizeRect.height - _rightMiddleSprite.height)/2;
_rightMiddleSprite.buttonMode = true;
_rightBottomSprite = drawResizeTab();
_rightBottomSprite.name = "RB";
_resizeHolder.addChild(_rightBottomSprite);
_rightBottomSprite.x = _resizeRect.width - 10;
_rightBottomSprite.y = _resizeRect.height - 10;
_rightBottomSprite.buttonMode = true;
//---------------
//Top middle resize tab
_topMiddleSprite = drawResizeTab();
_topMiddleSprite.name = "TM";
_resizeHolder.addChild(_topMiddleSprite);
_topMiddleSprite.x = (_resizeRect.width - _topMiddleSprite.width)/2;
_topMiddleSprite.y = - 10;
_topMiddleSprite.buttonMode = true;
//---------------------
//Bottom middle resize tab
_bottomMiddleSprite = drawResizeTab();
_bottomMiddleSprite.name = "BM";
_resizeHolder.addChild(_bottomMiddleSprite);
_bottomMiddleSprite.x = (_resizeRect.width - _bottomMiddleSprite.width)/2;
_bottomMiddleSprite.y = _resizeRect.height - 10;
_bottomMiddleSprite.buttonMode = true;
//---------------------
spr.addChild(_resizeHolder);
}
//For set the boundary for hotspot drag area
_dragRect = _spriteHolder.getBounds(_spriteHolder.parent);
_dragRect.width = (_dragRect.width - _resizeRect.width)+20;
_dragRect.height = (_dragRect.height - _resizeRect.height)+20;
_currentSprite.startDrag(false,_dragRect);
}
private function drawResizeTab():Sprite
{
var _tab:Sprite = new Sprite();
_tab.graphics.clear();
_tab.graphics.beginFill(0xFFCC00,0.8);
_tab.graphics.drawRect(0,0,20,20);
_tab.graphics.endFill();
_tab.addEventListener(MouseEvent.MOUSE_DOWN,onResizeTabDown);
stage.addEventListener(MouseEvent.MOUSE_UP,onResizeTabUp);
return _tab;
}
private function onMoveSprite(evt:MouseEvent):void
{
evt.updateAfterEvent();
}
private function onStopSprite(evt:MouseEvent):void
{
_currentSprite.stopDrag();
removeEventListener(MouseEvent.MOUSE_MOVE,onMoveSprite);
_currentSprite.addEventListener(MouseEvent.MOUSE_DOWN,onSpriteDown);
}
private function onResizeTabDown(evt:MouseEvent):void
{
evt.stopImmediatePropagation();
var _tab:Sprite = evt.target as Sprite;
_curTab = _tab;
_resizeStartX = _resizeRect.x;
_resizeStartY = _resizeRect.y;
_resizeWidth = _resizeRect.x+_resizeRect.width;
_resizeHeight = _resizeRect.y+_resizeRect.height;
_tab.startDrag();
stage.addEventListener(MouseEvent.MOUSE_MOVE,onSpriteResize);
stage.addEventListener(MouseEvent.MOUSE_UP,onStopDrag);
}
private function onStopDrag(evt:MouseEvent):void
{
_curTab.stopDrag();
stage.removeEventListener(MouseEvent.MOUSE_MOVE,onSpriteResize);
_currentSprite.addEventListener(MouseEvent.MOUSE_DOWN,onSpriteDown);
}
private function onSpriteResize(evt:MouseEvent):void
{
if(_curTab.name == "BM")
{
_resizeRect.bottom = Math.min(RESIZE_MAXIMUM_HEIGHT,_spriteHolder.mouseY);
}
if(_curTab.name == "TM")
{
_resizeRect.top = Math.max(0,_spriteHolder.mouseY);
}
if(_curTab.name == "RM")
{
_resizeRect.right = Math.min(RESIZE_MAXIMUM_WIDTH,_spriteHolder.mouseX);
}
if(_curTab.name == "LM")
{
_resizeRect.left = Math.max(0,_spriteHolder.mouseX);
}
if(_curTab.name == "LT")
{
_resizeRect.top = Math.max(0,_spriteHolder.mouseY);
_resizeRect.left = Math.max(0,_spriteHolder.mouseX);
}
if(_curTab.name == "RT")
{
_resizeRect.top = Math.max(0,_spriteHolder.mouseY);
_resizeRect.right = Math.min(RESIZE_MAXIMUM_WIDTH,_spriteHolder.mouseX);
}
if(_curTab.name == "RB")
{
_resizeRect.bottom = Math.min(RESIZE_MAXIMUM_HEIGHT,_spriteHolder.mouseY);
_resizeRect.right = Math.min(RESIZE_MAXIMUM_WIDTH,_spriteHolder.mouseX);
}
if(_curTab.name == "LB")
{
_resizeRect.bottom = Math.min(RESIZE_MAXIMUM_HEIGHT,_spriteHolder.mouseY);
_resizeRect.left = Math.max(0,_spriteHolder.mouseX);
}
if(_resizeRect.width <= HOTSPOT_MIN_SIZE && _resizeRect.height <= HOTSPOT_MIN_SIZE) {
_resizeRect.width = HOTSPOT_MIN_SIZE;
_resizeRect.height = HOTSPOT_MIN_SIZE;
if(_curTab.name == "LT") {
_resizeRect.x = _resizeWidth - _resizeRect.width;
_resizeRect.y = _resizeHeight - _resizeRect.height;
}
if(_curTab.name == "RT") {
_resizeRect.x = _resizeStartX;
_resizeRect.y = _resizeHeight - _resizeRect.height;
}
if(_curTab.name == "LB") {
_resizeRect.x = _resizeWidth - _resizeRect.width;
_resizeRect.y = _resizeStartY;
}
}
else if(_resizeRect.width <= HOTSPOT_MIN_SIZE && _resizeRect.height > HOTSPOT_MIN_SIZE)
{
_resizeRect.width = HOTSPOT_MIN_SIZE;
if(_curTab.name == "LT" _curTab.name == "LM")
_resizeRect.x = _resizeWidth - _resizeRect.width;
if(_curTab.name == "RT")
_resizeRect.x = _resizeStartX;
if(_curTab.name == "LB")
_resizeRect.x = _resizeWidth - _resizeRect.width;
}
else if(_resizeRect.width > HOTSPOT_MIN_SIZE && _resizeRect.height <= HOTSPOT_MIN_SIZE) {
_resizeRect.height = HOTSPOT_MIN_SIZE;
if(_curTab.name == "LT" _curTab.name == "TM")
_resizeRect.y = _resizeHeight - _resizeRect.height;
if(_curTab.name == "RT")
_resizeRect.y = _resizeHeight - _resizeRect.height;
if(_curTab.name == "LB")
_resizeRect.y = _resizeStartY;
}
_currentSprite.graphics.clear();
_currentSprite.graphics.beginFill(0xFF0000,0.8);
_currentSprite.graphics.drawRect(0,0,_resizeRect.width,_resizeRect.height); _currentSprite.graphics.endFill();
_currentSprite.x = _resizeRect.x;
_currentSprite.y = _resizeRect.y;
_resizeHolder.graphics.clear();
_resizeHolder.graphics.lineStyle(1,0x000000);
_resizeHolder.graphics.drawRect(0,0,_resizeRect.width,_resizeRect.height); _resizeHolder.graphics.endFill();
updatePosition(_resizeRect);
evt.updateAfterEvent();
}
private function updatePosition(_rect:Rectangle):void
{
_leftTopSprite.x = - 10; _leftTopSprite.y = - 10;
_leftMiddleSprite.x = - 10;
_leftMiddleSprite.y = (_rect.height - _leftMiddleSprite.height)/2;
_leftBottomSprite.x = - 10;
_leftBottomSprite.y = _rect.height - 10;
_rightTopSprite.x = _rect.width - 10;
_rightTopSprite.y = - 10;
_rightMiddleSprite.x = _rect.width - 10;
_rightMiddleSprite.y = (_rect.height - _rightMiddleSprite.height)/2;
_rightBottomSprite.x = _rect.width - 10;
_rightBottomSprite.y = _rect.height - 10;
_topMiddleSprite.x = (_rect.width - _topMiddleSprite.width)/2;
_topMiddleSprite.y = - 10;
_bottomMiddleSprite.x = (_rect.width - _bottomMiddleSprite.width)/2; _bottomMiddleSprite.y = _rect.height - 10;
}
private function onResizeTabUp(evt:MouseEvent):void
{
var _tab:Sprite = evt.target as Sprite; _tab.stopDrag();
_currentSprite.removeChildAt(0);
_resizeRect = _currentSprite.getBounds(_currentSprite.parent);
_currentSprite.addChild(_resizeHolder);
stage.removeEventListener(MouseEvent.MOUSE_MOVE,onSpriteResize);
}
]]> </mx:Script>
</mx:Application>

July 23, 2009

Enable and Disable ContextMenu in Flex with AS3

Hi,
We can enable and disable the context menu option from the context menu. In below example is very easy way to enable and disable the context menu option based on the context menu selection. Lets see the below example and enjoy

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import mx.managers.FocusManager;
import mx.core.UIComponent;
private var _spr:Sprite;
private var _contextMenu:ContextMenu;
private function onInit():void
{
var ui:UIComponent = new UIComponent();
_spr = new Sprite();
_spr.graphics.clear();
_spr.graphics.beginFill(0xFF0000,0.8);
_spr.graphics.drawRect(0,0,200,200);
_spr.graphics.endFill();
ui.addChild(_spr);
_spr.x = 20;
_spr.y = 20;
addChild(ui);
loadContextMenu();
}
private function loadContextMenu():void
{
_contextMenu = new ContextMenu();
_contextMenu.hideBuiltInItems();
var _selAll:ContextMenuItem = new ContextMenuItem("Select All Hotspot");
var _deSelAll:ContextMenuItem = new ContextMenuItem("Deselect All Hotspot");
var _delAll:ContextMenuItem = new ContextMenuItem("Delete All Hotspot");
_contextMenu.customItems.push(_selAll);
_contextMenu.customItems.push(_deSelAll);
_contextMenu.customItems.push(_delAll);
_contextMenu.customItems[1].enabled = false;
_contextMenu.customItems[2].enabled = false;
_selAll.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,menuItemSelect);
_delAll.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,menuItemSelect);
_deSelAll.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,menuItemSelect);
_spr.contextMenu = _contextMenu;
}
private function menuItemSelect(evt:ContextMenuEvent):void
{
var _custMenu:ContextMenuItem = evt.target as ContextMenuItem;
if(_custMenu.caption == "Select All Hotspot")
{
_contextMenu.customItems[0].enabled = false;
_contextMenu.customItems[1].enabled = true;
_contextMenu.customItems[2].enabled = true;
}
else
{
_contextMenu.customItems[0].enabled = true;
_contextMenu.customItems[1].enabled = false;
_contextMenu.customItems[2].enabled = false;
}
}
]]>
</mx:Script>
</mx:Application>

Navigate same or new window from Flex application

Hi,
In some Flex application need to navigate into flex application into other application. Those navigation can performs into the same window or new window by using the navigateToURL function from flash.net.navigateToURL. The below example contains two button for navigate to same as well as new window.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import flash.net.navigateToURL;
private function onNavigateNew():void
{
navigateToURL(new URLRequest("http://www.google.com"),"POST");
}
private function onNavigateSame():void
{
navigateToURL(new URLRequest("http://ww.yahoo.com"),"_self");
}
]]>
</mx:Script>
<mx:VBox width="200" height="200" paddingLeft="20" paddingTop="20">
<mx:Button label="New Window" click="onNavigateNew()"/>
<mx:Button label="Same Window" click="onNavigateSame()"/>
</mx:VBox>
</mx:Application>

July 20, 2009

Set the content at center position when browser resize in Flex with AS3

Hi,
In the below example i used the document class in Flex. i.e script class access from the external actionscript file. The content in the flex application can be set at center position dynamically when the browser resized. Document class the .mxml and .as file for the main application at the same location under the src folder. It can be placed in other location too. The stage will be accessed after the function call applicationCompleted. So you can set the stage related functionality after the applicationCompleted function then only it can be set the stage releated functions otherwise it should be null and its relevant functionality cannot be set. Just see the below example

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="100%" height="100%"
creationComplete="onInit()" applicationComplete="onAppComplete()">
<mx:Script source="TextWorks.as"/>
</mx:Application>

In above example the script tag refer the actionscript class. The actionscript class contains the entire main application scripts. TextWorks actionscript class coding as follows

import flash.display.Sprite;
import flash.events.Event;
import mx.core.UIComponent;

private var _spr:Sprite;
private var _ui:UIComponent;

private function onInit():void
{
_ui = new UIComponent();
_spr = new Sprite();
_spr.graphics.clear();
_spr.graphics.beginFill(0xFF0000,0.8);
_spr.graphics.drawRect(0,0,200,200);
_spr.graphics.endFill();
_ui.addChild(_spr);
addChild(_ui);
}
private function onAppComplete():void
{
stage.addEventListener(Event.RESIZE,onResize);
_spr.x = (stage.stageWidth - _spr.width)/2;
_spr.y = (stage.stageHeight - _spr.height)/2;
_ui.width = stage.stageWidth;
_ui.height = stage.stageHeight;
}
private function onResize(evt:Event):void
{
_spr.x = (stage.stageWidth - _spr.width)/2;
_spr.y = (stage.stageHeight - _spr.height)/2;
_ui.width = stage.stageWidth;
_ui.height = stage.stageHeight;
}

Run this application and see the sprite content will be placed at center position dynamically when the browser resize.

Call Javascript function from Flex application

Hi,
We can call the javascript function from Flex application to perform any specific activity that can be perfromed by the server. You can call the javascript function with parameters or without any parameter when function call. The parameters for the javascript function was separated by commas. The ExternalInterface class was used to call the javascript function from the flex application. The syntax for calling the javascript function as follows

ExternalInterface.call("Function Name","[parameters]");

July 13, 2009

Save text file and jpeg image in Adobe Air

Hi,
In below example for save the text files and image files in Adobe Air. Adobe Air was easily interact with the system local files. In this example i saved the text file as well as image files and it has the format as .jpg. When need to save the text file first it check whether the file are exit or not. If the file cannot be found means then the text file content saved as a new file. This below example save the files using the File Stream class. Try the below example was very nice and intresting one.

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.graphics.codec.PNGEncoder;
import flash.filesystem.*;
private var _stream:FileStream;
private function saveFile():void
{
var file:File = File.desktopDirectory.resolvePath("Test.txt");
_stream = new FileStream();
_stream.open(file,FileMode.WRITE);
_stream.writeUTFBytes(txt_area.text);
_stream.close();
}
private function saveImage():void
{
var file:File = File.desktopDirectory.resolvePath("test.jpg");
_stream = new FileStream();
_stream.open(file,FileMode.WRITE);
var _enc:PNGEncoder = new PNGEncoder();
var _bitmap:BitmapData = new BitmapData(img.width,img.height,true);
_bitmap.draw(img,new Matrix());
var bytes:ByteArray = _enc.encode(_bitmap);
_stream.writeBytes(bytes);
_stream.close();
}
]]>
</mx:Script>
<mx:VBox paddingTop="15" paddingLeft="15" paddingRight="15" paddingBottom="15">
<mx:HBox>
<mx:Label text="About Yourself:"/>
<mx:TextArea id="txt_area" width="250" height="125"/>
</mx:HBox>
<mx:HBox width="100%" horizontalAlign="center">
<mx:Image id="img" source="Test.jpg" width="200" height="150" horizontalAlign="center"/>
</mx:HBox>
<mx:HBox>
<mx:Button label="Save" click="saveFile()"/>
<mx:Button label="Save Image" click="saveImage()"/>
</mx:HBox>
</mx:VBox>
</mx:WindowedApplication>

July 08, 2009

Resize Sprite using the bottom resize tab in Flex

Hi,
The below example for resize the sprite using the resize tab at the bottomright position. By using the tab button to resize the sprite as width and height and it cannot be allow to change the postion of x and y.Try the below example it very nice one for resize the sprite based on resize tab move position and updates its width and height.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
private var _spr:Sprite;
private var _rect:Rectangle;
private var _resizeTab:Sprite;

private function onInit():void
{
var ui:UIComponent = new UIComponent();
_spr = new Sprite();
_spr.graphics.clear();
_spr.graphics.beginFill(0xFF0000,0.5);
_spr.graphics.drawRect(0,0,200,200);
_spr.graphics.endFill();
ui.addChild(_spr);
addChild(ui);
ui.x = 50;
ui.y = 20;

_spr.addEventListener(MouseEvent.MOUSE_DOWN,onStartResize);
}

private function onStartResize(evt:MouseEvent):void
{
var _rect:Rectangle = _spr.getBounds(_spr.parent);
if(!_resizeTab)
{
_resizeTab = new Sprite();
_resizeTab.graphics.clear();
_resizeTab.graphics.beginFill(0x0000FF,0.8);
_resizeTab.graphics.drawRect(0,0,20,20);
_resizeTab.graphics.endFill();

_resizeTab.x = _rect.width - 10;
_resizeTab.y = _rect.height - 10;

_spr.addChild(_resizeTab);
_resizeTab.cacheAsBitmap = false;
_resizeTab.addEventListener(MouseEvent.MOUSE_DOWN,onResizeDown);
_resizeTab.addEventListener(MouseEvent.MOUSE_UP,onResizeUp);
}
else
return;
}

private function onResizeDown(evt:MouseEvent):void
{
var _sp:Sprite = evt.target.parent as Sprite;
_rect = _sp.getBounds(_sp.parent);
_resizeTab.startDrag();
addEventListener(MouseEvent.MOUSE_MOVE,onMove);
}

private function onMove(evt:MouseEvent):void
{
var _sp:Sprite = _resizeTab.parent as Sprite;
_rect.bottomRight = new Point(_sp.mouseX,_sp.mouseY);
_sp.graphics.clear();
_sp.graphics.beginFill(0xFF0000,0.4);
_sp.graphics.drawRect(0,0,_rect.width,_rect.height);
_sp.graphics.endFill();

var summa:Rectangle = _resizeTab.getBounds(_resizeTab.parent);
_resizeTab.x = _rect.width - (summa.width/2);
_resizeTab.y = _rect.height - (summa.height/2);
evt.updateAfterEvent();
}

private function onResizeUp(evt:MouseEvent):void
{
removeEventListener(MouseEvent.MOUSE_MOVE,onMove);
_resizeTab.stopDrag();
}

]]>
</mx:Script>
</mx:Application>

Load swf content into the Sprite in AS3

Hi,
In some of the post has mention as cannot possible to load the swf content inside the Sprite using the Loader class in AS3. But i try to load the swf content into the sprite using the Loader class. In this below example to load the loader directly instead of adding the child as loader.content. If you are try to load the child as loader.content means it throws an error as AVM1 object voliation for load the AVM2 oject into AVM1 Object. So you can add the child of sprite as loader it can possible to load the swf content and you can work over that.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
import flash.events.KeyboardEvent;
import mx.controls.SWFLoader;

private var ui:UIComponent;
private var _spr:Sprite;
private var loader:Loader;

private function onInit():void
{
ui = new UIComponent();
_spr = new Sprite();
ui.addChild(_spr);
addChild(ui);

loader = new Loader();
loader.load(new URLRequest("test.swf"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoadComplete);
}

private function onLoadComplete(e:Event):void
{
_spr.addChild(loader);
}

]]>
</mx:Script>
</mx:Application>

Simple Slideshow with Fade Effect

Hi,
In some of the slide show applications slide transition will be performed before the second image loaded. So the slide show application has blank screen without any images on screen after loading the second image then it start showing the image with effect. In below example avoid the blank screen and it will check whether the second image was loaded or not. If loaded the image it start the transition otherwise it remains on the first image to avoid the blank screen. In below example has avoid the blank screen and apply smooth fade effect when transistions.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import mx.effects.Fade;
import mx.controls.Button;
import mx.containers.HBox;
import mx.controls.ProgressBar;
import mx.core.UIComponent;

private var image_container:UIComponent;
private var first_mc:Sprite;
private var second_mc:Sprite;
private var load_mc:Sprite;
private var _selectedIndex:Number=0;
private var timer:Timer;
private var _imgArray:Array = ["http://www.digitalphotoartistry.com/rose1.jpg","http://blogs.warwick.ac.uk/images/spjyoung/2006/02/20/rose.jpg","http://www.mccullagh.org/db9/1ds2-2/rose-side-view.jpg"];

private function onInit():void
{
image_container = new UIComponent();
first_mc = new Sprite();
image_container.addChild(first_mc);
second_mc = new Sprite();
image_container.addChild(second_mc);
addChild(image_container);

image_container.width = 400;
image_container.height = 400;
image_container.x = 20;
image_container.y = 20;

load_mc = first_mc;
loadImage();
startTimer();
}

private function startTimer():void
{
timer = new Timer(5000);
timer.addEventListener(TimerEvent.TIMER,loadImges);
timer.start();
}

private function loadImges(evt:TimerEvent):void
{
if(_selectedIndex >= _imgArray.length-1)
{
_selectedIndex = -1;
}
else
{
_selectedIndex++;
loadImage();
}
}

private function loadImage():void
{
var urlLoader:Loader = new Loader();
var urlRequest:URLRequest =new URLRequest(_imgArray[_selectedIndex]);
urlLoader.contentLoaderInfo.addEventListener(Event.OPEN,onImageOpen);
urlLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImageLoaded);

try
{
urlLoader.load(urlRequest);
}
catch(err:Error)
{
trace("Error");
}
}

private function onImageOpen(evt:Event):void
{
if(first_mc.numChildren > 0)
first_mc.removeChildAt(0);
if(second_mc.numChildren > 0)
second_mc.removeChildAt(0);

var num:Number = switchNumber(_selectedIndex);
if(num == 1)
{
load_mc = first_mc;
fadeOutImage(second_mc);
fadeInImage(first_mc);
}
else
{
load_mc = second_mc;
fadeOutImage(first_mc);
fadeInImage(second_mc);
}
}

private function onImageLoaded(evt:Event):void
{
load_mc.addChild(evt.target.content);
load_mc.width = 380;
load_mc.height = 300;
}

private function switchNumber(num:Number):Number
{
var ind:Number = num%2;
return (ind == 0)?1:2;
}

private function fadeInImage(target:Sprite):void
{
var _fadeIn:Fade = new Fade(target);
_fadeIn.alphaFrom = 0;
_fadeIn.alphaTo = 1;
_fadeIn.duration = 400;
_fadeIn.play();
}

private function fadeOutImage(target:Sprite):void
{
var _fadeOut:Fade = new Fade(target);
_fadeOut.alphaFrom = 1;
_fadeOut.alphaTo = 0;
_fadeOut.duration = 400;
_fadeOut.play();
}

]]>
</mx:Script>
</mx:Application>

Working with local system files in Flex3.2 SDK and FlashPlayer10

Hi,
In below example for accessing the local system xml files and read the xml content and set the input to the List control. The seelcted xml content as shown in Textarea control also. Whenever click the image from the List control its relevant image is shown. It must need the Flex sdk3.2 and Flash player10 then only access the function of the Flash player10 as load() and save() otherwise in the below example cannot be work.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;
import flash.net.FileReference;
import flash.utils.ByteArray;

private var _fileBrowse:FileReference;
private var _imgStr:String;
private var _listProvider:Array;

private function onClick():void
{
_fileBrowse = new FileReference();
_fileBrowse.addEventListener(Event.CANCEL,onCancel);
_fileBrowse.addEventListener(Event.SELECT,onFileSelect);
_fileBrowse.browse();
}

private function onCancel(evt:Event):void
{
_fileBrowse = null;
}

private function onFileSelect(evt:Event):void
{
_fileBrowse.addEventListener(Event.COMPLETE,onComplete);
_fileBrowse.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
_fileBrowse.load();
}

private function onComplete(evt:Event):void
{
var _data:ByteArray = _fileBrowse.data;
txt_area.text = _data.readUTFBytes(_data.bytesAvailable);
_imgStr = txt_area.text;
_fileBrowse = null;
loadXML();
}

private function ioErrorHandler(evt:IOErrorEvent):void
{
trace("Io Error");
}

private function loadXML():void
{
var _xml:XML;
_listProvider = new Array();

if(_imgStr != "")
{
_xml = new XML(_imgStr);
var _xmlList:XMLList = XMLList(_xml.image);
for(var i:int=0;i<_xmlList.length();i++)
{
_listProvider.push({label:_xmlList[i].@name,path:_xmlList[i].@path});
}
lst.dataProvider = _listProvider;
}
}

private function onItemClick():void
{
img.source = lst.selectedItem.path;
}

]]>
</mx:Script>
<mx:HBox paddingLeft="20" paddingTop="20">
<mx:VBox>
<mx:TextArea id="txt_area" width="400" height="200"/>
<mx:List id="lst" width="400" height="120" itemClick="onItemClick()"/>
<mx:Button label="open" click="onClick()"/>
</mx:VBox>
<mx:HBox>
<mx:Image id="img" width="400" height="400"/>
</mx:HBox>
</mx:HBox>
</mx:Application>

The example xml as follows

<?xml version="1.0" encoding="UTF-8"?>
<images>
<image name="image1" path="http://www.digitalphotoartistry.com/rose1.jpg"/>
<image name="image2" path="http://blogs.warwick.ac.uk/images/spjyoung/2006/02/20/rose.jpg"/>
<image name="image3" path="http://www.mccullagh.org/db9/1ds2-2/rose-side-view.jpg"/>
</images>

Hightlight the selection of Sprite in Flex

Hi,
In Sprite highlighted by using the graphics for change the color selection. The getBounds() function was used to get the boundary area of the sprite based on that we can draw the graphics again with different selection color. After complete the graphics draw then placed the sprite by its position of x and y. Whenever need to change the color selection we must need redraw the sprite using the graphics. In the folowing example very nice one for selecting or highlighted the sprite based on mouse down event.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;

private var _spr:Sprite;
private var _curSpr:Sprite;
private var _prevSpr:Sprite;

private function onInit():void
{
var ui:UIComponent = new UIComponent();
_spr = new Sprite();
_spr.graphics.clear();
_spr.graphics.beginFill(0xFF0000);
_spr.graphics.drawRect(0,0,200,200);
_spr.graphics.endFill();
_spr.addEventListener(MouseEvent.MOUSE_DOWN,onSelect);
_spr.x = 20;
_spr.y = 30;
ui.addChild(_spr);

_spr = new Sprite();
_spr.graphics.clear();
_spr.graphics.beginFill(0xFF0000);
_spr.graphics.drawRect(0,0,200,200);
_spr.graphics.endFill();
_spr.addEventListener(MouseEvent.MOUSE_DOWN,onSelect);
ui.addChild(_spr);
_spr.x = 230;
_spr.y = 25;

addChild(ui);
}

private function onSelect(evt:MouseEvent):void
{
_prevSpr = _curSpr;
if(_prevSpr != null)
setSelect(_prevSpr,0xFF0000);
_curSpr = evt.target as Sprite;
setSelect(_curSpr,0x00FF00);
}

private function setSelect(spr:Sprite,color:uint):void
{
var rect:Rectangle = spr.getBounds(spr.parent);

spr.graphics.clear();
spr.graphics.beginFill(color);
spr.graphics.drawRect(0,0,rect.width,rect.height);
spr.graphics.endFill();

spr.x = rect.x;
spr.y = rect.y;
}

]]>
</mx:Script>
</mx:Application>

Refresh Flex page using Javascript function in AS3

Hi,
In Flex once the values get updated we need to refresh the felx content dynamically. Here i did one example for refresh the flex page by calling the javascript function when click the button in flex application. Its very simple way to refresh the flex page whenever you wants by using the following javascript function calls.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import flash.net.navigateToURL;
private function onRefresh():void
{
var ref:URLRequest = new URLRequest("javascript:location.reload(true)");
navigateToURL(ref,"_self");
}
]]>
</mx:Script>
<mx:Button label="Refresh" click="onRefresh()"/>
</mx:Application>

Drag the Sprite using the Shift Key and Mouse Down event in AS3

Hi,
This following example for drag the sprite when holding the shift key in the Keyboard. The Shify key was released then the sprite cannot be moved furtur and it stop drag into the selected dragged area. The selected sprite should be focus then only it can work the functionality of the keyboard and check whether pressed the shift key or not. The Display object cannot be focus use the code as stage.focus property as currently selected Display object. This property helps to focus the current Display object selection and then drag the sprite based on Shift Key was pressed.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="onKeySet()" creationComplete="onInit()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
private var _spr:Sprite;

private function onInit():void
{
var ui:UIComponent = new UIComponent();
_spr = new Sprite();
_spr.graphics.clear();
_spr.graphics.beginFill(0xFF0000,0.7);
_spr.graphics.drawRect(0,0,500,500);
_spr.graphics.endFill();
ui.addChild(_spr);
addChild(ui);
}

private function onKeySet():void
{
stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
}

private function onKeyDown(evt:KeyboardEvent):void
{
stage.focus = _spr;
_spr.focusRect = false;
if(evt.keyCode == 16)
{
_spr.addEventListener(MouseEvent.MOUSE_DOWN,onDownSprite);
_spr.addEventListener(MouseEvent.MOUSE_UP,onUpSprite);
}
}

private function onKeyUp(evt:KeyboardEvent):void
{
if(evt.keyCode == 16)
{
_spr.removeEventListener(MouseEvent.MOUSE_DOWN,onDownSprite);
_spr.removeEventListener(MouseEvent.MOUSE_UP,onUpSprite);
}
}

private function onDownSprite(evt:MouseEvent):void
{
_spr.addEventListener(MouseEvent.MOUSE_MOVE,onMoveSprite);
}

private function onMoveSprite(evt:MouseEvent):void
{
_spr.startDrag();
evt.updateAfterEvent();
}

private function onUpSprite(evt:MouseEvent):void
{
_spr.stopDrag();
_spr.removeEventListener(MouseEvent.MOUSE_MOVE,onMoveSprite);
}

]]>
</mx:Script>
</mx:Application>

Swap two xml nodes in XML

Hi,
The following example explain about the swapping two nodes based on the node index value.The newly updated the swap xml is maintained in the main XML. The swap XML was considered as a new xml then only it should be swap properly in XML otherwise it cannot perfefectly swap and reflect the changes to the XML.

<?xml version="1.0" encoding="utf-8"?>
<mx:application mx="http://www.adobe.com/2006/mxml" layout="absolute" creationcomplete="onInit()">
<mx:script>
<![CDATA[
private var _initXML:XML;
private var _xmlList:XMLList;

private function onInit():void
{
_initXML = XML("");
_xmlList = XMLList(_initXML.Fruits.fruit);
txt_area.text = _initXML.toXMLString();
}

private function onButtonClick():void
{
txt_area.text = swapXML(int(txt_old.text),int(txt_new.text));
}

private function swapXML(ind1:int,ind2:int):XML
{
var xml1:XML = new XML(_xmlList[ind1]);
var xml2:XML = new XML(_xmlList[ind2]);
_xmlList[ind1] = xml2;
_xmlList[ind2] = xml1;
return _initXML;
}
]]>
</mx:Script>
<mx:vbox paddingtop="10" paddingleft="10">
<mx:textarea id="txt_area" width="450" height="300">
<mx:hbox>
<mx:text text="Old Depth:" width="100">
<mx:textinput id="txt_old" width="100">
</mx:HBox>
<mx:hbox>
<mx:text text="New Depth:" width="100">
<mx:textinput id="txt_new" width="100">
</mx:HBox>
<mx:hbox paddingleft="30">
<mx:button label="Change" click="onButtonClick()">
</mx:HBox>
</mx:VBox>
</mx:Application>

MouseMove problem in AS3

Hi,
In Actionscript3 Mousemove events assigned to the display objects it can be fired gradually when the mouse will be focused on the display object assigned to which it was assigned. When mouse goes off or outside of the display objects it stop firing the mousemove event. If you drag a display object using the mousemove event to stop functioning the mousemove event if you move the mouse too fast preventing the display object being dragged until the mouse is back over the display object.

Problem in accessing Webservice when send xml as input to Webservice class in AS3

Hi,
I faced the problem when send the xml value as the input to the webservice class. I use e4x format for access the webservice. When xml as send as the input to the webservice class it cannot call the webservice class and report as warning message. Then i set the xmlSpecialCharsFilter function for the web service class and its change the value of object type to string value type and then send the value. After it call the webservice class successfully and return the result from the webservice class. The following way i can use to solve the problem for not accessing the webservice

var webService:WebService = new WebService();
webService.xmlSpecialCharsFilter = filterVal;

The xmlSpecialCharsFilter as function it will filter the special characters and change the object type values to string values. The filterVal function definition as follows

private function filterVal(val:Object):String
{
return val.toString();
}


June 29, 2009

Dynamically draw ploygon in Flex

Hi,
In below example is very nice one for dynamically add the polygon based on the mouse click and it allows only for four sides. The below example code fully written in action script.

private var drawPanel:Sprite;
private var numSpot:Number = 0;
private var line:Shape;
private var _lineArr:Array;
private function onDrawTriangle():void
{
var ui:UIComponent = new UIComponent();
drawPanel = new Sprite();
drawPanel.graphics.clear();
drawPanel.graphics.lineStyle(2, 0xFF0000);
drawPanel.graphics.beginFill(0xDEFACE);
drawPanel.graphics.drawRect(0,0,300,300);
drawPanel.graphics.endFill();
ui.addChild(drawPanel);
addChild(ui);
ui.x = 20;
ui.y = 20;

_lineArr = new Array();
line = new Shape();
drawPanel.addEventListener(MouseEvent.CLICK,onAddPoint);
}

private function onAddPoint(evt:MouseEvent):void
{
if(numSpot <= 4)
{
var point:Sprite = new Sprite();
point.graphics.clear();
point.graphics.lineStyle(0,0x0000FF);
point.graphics.beginFill(0x0000FF);
point.graphics.drawCircle(0,0,5);
point.graphics.endFill();

point.x = evt.localX;
point.y = evt.localY;
_lineArr.push({x:point.x,y:point.y});
drawPanel.addChild(point);
if(numSpot > 0)
drawLine();
numSpot++;
}
}

private function drawLine():void
{
line.graphics.clear();
line.graphics.lineStyle(2,0x000000);
if(_lineArr.length > 2)
line.graphics.beginFill(0xFF0000,0.5);
line.graphics.moveTo(_lineArr[0].x,_lineArr[0].y);
for(var i:int=1;i<_lineArr.length;i++)
{
line.graphics.lineTo(_lineArr[i].x,_lineArr[i].y);
}
line.graphics.lineTo(_lineArr[0].x,_lineArr[0].y);
if(_lineArr.length > 2)
line.graphics.endFill();
drawPanel.addChildAt(line,0);
}

Dynamically draw circle based on mouse move in Flex

Hi,
The circle dynamically drawn at mouse starting point and its size varies based on the mouse movement. In below example is for draw the circle dynamically in action script code in flex

private var _cir:Sprite;
private var _rect:Rectangle;
private function onDrawCircle():void
{
var ui:UIComponent = new UIComponent();
var drawPanel:Sprite = new Sprite();
drawPanel.graphics.clear();
drawPanel.graphics.lineStyle(2, 0xFF0000);
drawPanel.graphics.beginFill(0xDEFACE);
drawPanel.graphics.drawRect(0,0,300,300);
drawPanel.graphics.endFill();
ui.addChild(drawPanel);
addChild(ui);
ui.x = 20;
ui.y = 20;

_cir = new Sprite();
_cir.graphics.clear();
_cir.graphics.beginFill(0x00FF00,0.5);
_cir.graphics.drawCircle(0,0,0);
_cir.graphics.endFill();
drawPanel.addChild(_cir);
_cir.x = 10;
_cir.y = 10;
_rect = new Rectangle();
addEventListener(MouseEvent.MOUSE_DOWN,onCircleDown);
addEventListener(MouseEvent.MOUSE_UP,onCircleUp);
}

private function onCircleDown(evt:MouseEvent):void
{
var spr:Sprite = evt.target as Sprite;
_rect = spr.getBounds(spr.parent);
addEventListener(MouseEvent.MOUSE_MOVE,onCircleMove);
}

private function onCircleMove(evt:MouseEvent):void
{
var spr:Sprite = evt.target.parent as Sprite;
_rect.bottomRight = new Point(spr.mouseX,spr.mouseY);

_cir.graphics.clear();
_cir.graphics.beginFill(0x00FF00,0.5);
_cir.graphics.drawCircle(_rect.width/2, _rect.width/2, _rect.width/2);
_cir.graphics.endFill();
}

private function onCircleUp(evt:MouseEvent):void
{
removeEventListener(MouseEvent.MOUSE_MOVE,onCircleMove);
}

Custom Webservice class for access web services

Hi,
I am developed the web service class for accessing the webservice and webservice input as array values and this webservice class return the xml values to the call back function and based on the response we can proceed

package service
{
import mx.managers.CursorManager;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.soap.LoadEvent;
import mx.rpc.soap.WebService;

public class URLWebService
{
private var _argValues:Array;
private var _serviceURL:String = "";
private var _operationName:String = "";
private var _callbackObject:Object;
private var _callbackFun:Function;
private var webService:WebService;
private var _showBusyCursor:Boolean = false;
private var _isArguments:Boolean = false;

private var _serviceError:MessageServices = new MessageServices("Service Load Problem","Warning");
private var _webServiceURLError:MessageServices = new MessageServices("Webservice URL Error","Warning");

public function get serviceURL():String
{
return _serviceURL;
}
public function set serviceURL(val:String):void
{
if(_serviceURL != val)
_serviceURL = val;
}

public function get operationName():String
{
return _operationName;
}
public function set operationName(val:String):void
{
if(_operationName != val)
_operationName = val;
}

public function get showBusyCursor():Boolean
{
return _showBusyCursor;
}
public function set showBusyCursor(val:Boolean):void
{
if(_showBusyCursor != val)
_showBusyCursor = val;
}

public function get argValues():Array
{
return _argValues;
}
public function set argValues(val:Array):void
{
if(_argValues != val)
_argValues = val;
}

public function get callbackObject():Object
{
return _callbackObject;
}
public function set callbackObject(val:Object):void
{
if(_callbackObject != val)
_callbackObject = val;
}

public function get callbackFun():Function
{
return _callbackFun;
}
public function set callbackFun(val:Function):void
{
if(_callbackFun != val)
_callbackFun = val;
}

public function get serviceError():MessageServices
{
return _serviceError;
}
public function set serviceError(val:MessageServices):void
{
if(_serviceError != val)
_serviceError = val;
}

public function get webServiceURLError():MessageServices
{
return _webServiceURLError;
}
public function set webServiceURLError(val:MessageServices):void
{
if(_webServiceURLError != val)
_webServiceURLError = val;
}

public function URLWebService()
{

}

public function load(argVal:Array=null,callbackObject:Object=null,callbackFunction:Function=null):void
{
if(_serviceURL && _serviceURL != "")
{
if(argVal)
{
_argValues = argVal;
_isArguments = true;
}
if(_showBusyCursor)
{
CursorManager.setBusyCursor();
}

webService = new WebService();
webService.wsdl = _serviceURL;
webService[_operationName].resultFormat = "e4x";
webService[_operationName].addEventListener(ResultEvent.RESULT,onResult);
webService[_operationName].addEventListener(FaultEvent.FAULT,onFault);
webService.addEventListener(LoadEvent.LOAD,onLoad);

webService.loadWSDL();
_callbackObject = callbackObject;
_callbackFun = callbackFunction;
}
else
_webServiceURLError.show();
}

private function onResult(evt:ResultEvent):void
{
if(_callbackObject && _callbackFun != null)
{
var xml:XML = new XML(evt.result);
var ResultXML:XML;
try
{
ResultXML = XML(xml.*.*);
if(_showBusyCursor)
CursorManager.removeBusyCursor();

}
catch(e:Error)
{
ResultXML = new XML("Sucessfully Added");
}
_callbackFun.call(_callbackObject,ResultXML);
}
else
_serviceError.show();
webService[_operationName].removeEventListener(ResultEvent.RESULT,onResult);
}

private function onFault(evt:FaultEvent):void
{
_serviceError.show();
webService[_operationName].removeEventListener(FaultEvent.FAULT,onFault);
}

private function onLoad(evt:LoadEvent):void
{
if(_isArguments)
{
_isArguments = false;
var input:Object = new Object();
for(var i:int=0;i<_argValues.length;i++)
{
input[_argValues[i].name] = _argValues[i].value;
}
webService[_operationName].arguments = input;
}
webService[_operationName].send();
webService.removeEventListener(LoadEvent.LOAD,onLoad);
}
}}

Dynamically add or remove the ToggleButton controls in Flex

Hi,
We can dynamically add the button controls into toggle button controls by following way

var obj:Object = new Object();
obj.icon = _iconArray[_buttonIndex];
_buttonArray.push(obj);
_togg.dataProvider = _buttonArray;

as well as we can remove the button controls from the toggle buttoncontrols by following way

_buttonArray.pop();
_togg.dataProvider = _buttonArray;

Dynamically set ToggleButton contol in Flex

Hi,
We can set the toggle button control dynamically based on the xml or array values. In below function use icon array as the array for the icon assets for the button controls and panel was the container for adding the ToggleButtonBar controls.

private function onLoadTools():void
{
var _buttonArray:Array = new Array();
var _togg:ToggleButtonBar = new ToggleButtonBar();
_togg.direction = "vertical";
_togg.toggleOnClick = false;
for(var i:int=0;i<_iconArray.length-1;i++)
{
var obj:Object = new Object();
obj.icon = _iconArray[i];
_buttonArray.push(obj);
}
_togg.dataProvider = _buttonArray;
panel.addChild(_togg);
_togg.addEventListener(ItemClickEvent.ITEM_CLICK,onToolsClick);
}

Flex Programming Architecture

Hi,
The Flex programming style may be varied based on the programmers. Some of the programmers are more familiar in writing coding in a class style and some of them familiar in writing the mxml components. Here i mention the some of the ways you can create the Flex programming

1)the entire project can be coded in actionscript
2)actionscript can be embedded into your MXML file using the tags
3)actionscript can be used to create custom classes/components, and to extend any of the flex classes.
4) actionscript functions can be called from within components declared with MXMLfor example:

June 08, 2009

Access local files in Adobe Flex 3.2 sdk and FP10

Hi,
The Flex3.2 sdk and Flash Player 10 will support for access local files in your system. The file stream class used to access the local system files as bytes array and File Reference class has new methods as load () for load the local system files and save () method for save the modified content into local system. These Load () and save () method only accessed by Flex3.2 sdk and FlashPlayer10 only. If you already have Flex3 sdk then you can upgrade Flex3.2 sdk or latest version of sdk and check whether you are using the FlashPlayer10 version or not. If you are not using the Flash player10 version then upgrade the Flash player also. Then you can play with accessing the local system files.