Flex3.0&AS3 2009. 1. 29. 14:24

Datagrid labelfuntion


이 옵션은 db로부터 데이타값을 받고  datagrid에 바인딩시킬때 원하는 포멧형식을 지정해줄때 사용하면 좋을듯하다.

일반적으로  db로부터 리턴받는 타입에 따라서 item부분을 Object 혹은 xml로 리턴받게된다.
상황에 따라서 선택적으로 사용하면될듯..

public static function labelFuncDateFormat(item:Object,column:DsDataGridColumn):String{
  var strVal:String = "";
  var tmpStr:String = item[column.dataField] as String;
  if(tmpStr == "" || tmpStr == null){
   strVal = "";
  else if(tmpStr.length > 8){
   strVal = tmpStr.substr(0,4)+"-"+tmpStr.substr(4,2)+"-"+tmpStr.substr(6,2);   
  }
  return strVal;
}


<mx:DataGridColumn headerText="현재날짜"
            textAlign="left"
            dataField="EDITDATE" labelFunction=" labelFuncDateFormat"/>
Flex3.0&AS3 2008. 12. 9. 15:50

Flex3.0 ] Module Class Lv1.



ModuleClac 클래스는 간단한 수식 계산을 담당하며 메인어플리케이션 클래스에서 모듈을 이용해서
해당 클래스를 로드하여 계산을 처리하는 간단한 예제이다.



 ModuleClac.mxml (모듈클래스를 상속)

<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="400" height="300">
 <mx:Script>
  <![CDATA[
   public function SumClac(m1:Number, m2:Number):Number{
    return m1+m2;
   }
  ]]>
 </mx:Script>
</mx:Module>


 ModuleTest.mxml (모듈테스트 apllication)

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
 <mx:Script>
  <![CDATA[
   import mx.core.IFlexModuleFactory;
   import mx.modules.IModuleInfo;
   import mx.modules.ModuleManager;
   
   private var obModule:Object;
   
   public var iModuleInfo:IModuleInfo;
   public var iReadImg:IReadImg;
   
   
   /*
   Module swf를 설정해서 모듈 정보 객체를 생성
   Module 정보 객체는  로더객체라고 생각하면됨
   */
   private function GetModule(mURL:String):void{
    iModuleInfo = ModuleManager.getModule(mURL);
    iModuleInfo.addEventListener("ready",fnReady);
    iModuleInfo.load();
   }
   
   private function fnReady(e:Event):void{
    e.target.removeEventListener("ready",fnReady);   
    /*
       모듈정보객체에게 다운받은 모듈을 생성
      생성객체는  object로 변수에 저장한다.
    */

    obModule = iModuleInfo.factory.create();
    tiResult.text = obModule.SumClac(10,30).toString();
   }
   
   
  ]]>
 </mx:Script>
 <mx:TextInput x="27" y="19" width="93" id="tiResult"/>
 <mx:Image id="imgView" width="300" height="200"/>
 <mx:Button x="128" y="19" label="ModuleLoad" click="GetModule('ModuleClac.swf')"/>
</mx:Application>


첫번째 모듈클래스는 모듈클래스를 상속받아 만든 클래스입니다.
일반적으로 모듈클래스를 상속받는 이유는 컴포너트를 배치하는 목적입니다.
그러나 위에 예의 경우 단순한 로직처리를 위한 부분밖에 없기 때문에 컴포넌트를 배치할수잇는 모듈클래스보다 가벼운
ModuleBase라는 클래스를 상속받아 처리하는 SimpleClass.as 입니다.


package{
 import flash.events.Event;
 
 import mx.core.Application;
 import mx.modules.ModuleBase;
 
 public class SimpleClass extends ModuleBase{

  public function SimpleClass(){}
  
  public function SumClac(m1:Number, m2:Number):Number{
   return m1+m2;
  }
  
  
 }



중요한것은 위의 코드를 테스트 하기 위해서는 as파일을 swf로 변환시켜줘야 합니다.
그러기 위해서는 이클립스에서 약간의 작업이 필요합니다.

프로젝트에서 마우스오른쪽버튼클릭후 properties
아래그림에서 add하여 아까작성한 as 및 mxml을 선택하면 이클립스에서 swf로 파일을 자동적으로 생성해줍니다.

Flex3.0&AS3 2008. 12. 1. 14:29

flex3.0] Binding 바인딩 방법


플렉스에서는 바인딩할수있는 여러가지 방법이 있는데 바인딩 처리 방법입니다


Method1.
                {} 를 이용한 방법

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle"
    horizontalAlign="center" backgroundGradientColors="[0x000000,0x323232]" viewSourceURL="srcview/index.html">

    <mx:TextInput id="myTI" text="Type something here"/>
    <mx:Text id="myText" text="{myTI.text}" color="white"/>
    <mx:Text id="myTextUpper" text="{myTI.text.toUpperCase()}" color="white"/>
    <mx:Text id="myTextLength" text="{myTI.text.length}" color="white"/>

</mx:Application>




 

Method2.
                {} 를 이용한 방법

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle"
    horizontalAlign="center" backgroundGradientColors="[0x000000,0x323232]">
    <mx:Text text="Type into either field" color="white"/>
   
    <mx:TextInput id="myTI1" text="{myTI2.text}"/>
    <mx:TextInput id="myTI2" text="{myTI1.text}"/>
   
</mx:Application>



 

Method3.
                <Binding > 테그를 이용한 방법

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle"
    horizontalAlign="center" backgroundGradientColors="[0x000000,0x323232]">

    <mx:TextInput id="myTI" text="Type something here"/>
    <mx:Text id="myText" color="white"/>  

    <mx:Binding source="myTI.text" destination="myText.text"/>
</mx:Application>




 

Method4.
                ActionScript에서 BindingUtils.bindProperty를 이용한 바인딩

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle"
    horizontalAlign="center" backgroundGradientColors="[0x000000,0x323232]">
   
    <mx:Script>
        <![CDATA[
            import mx.binding.utils.*;
           
            // Define data binding.
            public function initBindingHandler():void {
            BindingUtils.bindProperty(myText, "text", myTI, "text");
            }
          ]]>   
    </mx:Script>

    <mx:TextInput id="myTI" text="Type something here"/>
    <mx:Text id="myText" preinitialize="initBindingHandler();" color="white"/>
</mx:Application>



Method5.
                [Bindable]키워드를 이용한 바인딩
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle"
    horizontalAlign="center" backgroundGradientColors="[0x000000,0x323232]">
   
    <mx:Script>
        <![CDATA[
            // Define public vars for tracking temps.
            [Bindable]
            public var highTemp:Number = 90;
   
            [Bindable]
            public var lowTemp:Number = 55;
        ]]>   
    </mx:Script>
   
    <mx:Text text="High: {highTemp}   Low: {lowTemp}" color="white"/>

    <mx:Button label="Winter Temps" click="highTemp=50; lowTemp=10;"/>
    <mx:Button label="Summer Temps" click="highTemp=95; lowTemp=80;"/>
</mx:Application>





Flex3.0&AS3 2008. 12. 1. 14:05

updateDisplayList() 알아보기


updataDisplayList() 메서드는 스타일에 관련 셋팅을 변경하거나 설정할때 호출되어지는 메서드이다.

플렉스에서는 addChild()를 하여 컨터이너에 콤포넌트를 추가하게되면 자동적으로 invalidateDisplayList()메서드를 호출하게 되고 이 메서드가 호출된후에 updataDisplayList()가 호출되어 시각화되게 되는것이다.

따라서 UIComponent 클래스를 구현한 모든 클래스에서는 스타일변경이 필요한경우에는 위의 메서드를 오버라이드해서 작업을 해주면된다.

protected function updateDisplayList(unscaledWidth:Number,
    unscaledHeight:Number):void

unscaledWidth Specifies the width of the component, in pixels, in the component's coordinates, regardless of the value of the scaleX property of the component. This is the width of the component as determined by its parent container.

unscaledHeight Specifies the height of the component, in pixels, in the component's coordinates, regardless of the value of the scaleY property of the component. This is the height of the component as determined by its parent container.

Scaling occurs in Flash Player, after updateDisplayList() executes. For example, a component with an unscaledHeight value of 100, and with a scaleY property of 2.0, appears 200 pixels high in Flash Player.

/*아래 일부코드는 updateDisplayList()메서드를 오버라이드한 일부 첨부파일중 일부 코드이다.*/
 override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
         {
            super.updateDisplayList(unscaledWidth, unscaledHeight);

            if (data != null && listData != null && data[DataGridListData(listData).dataField] < 0)
            {
                 setStyle("color", 0xFF0000);
             }
             else
             {
                 setStyle("color", 0x009900);
             }

        }

자세한 내용은 아래 url을 참조
http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=ascomponents_advanced_148_16.html


Sample>

Flex3.0&AS3 2008. 10. 23. 18:15

Tree To ComboBox


<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" height="280" width="443">

<mx:XML id="xmlData">
<root> 
            <folder label="Stock" isBranch="true"> 
            </folder>             
            <folder label="Entertainment" isBranch="true">
                  <folder label="지상파 방송" isBranch="true" />
                  <folder label="케이블 방송" isBranch="true">
                          <Pfolder label="인천" />
                          <Pfolder label="수원" />
                  </folder>
            </folder>
           
            <folder label="Sports">
                  <Pfolder label="야구" />
                  <Pfolder label="축구" />
                  <Pfolder label="농구" />
                  <Pfolder label="배구" />
            </folder>
</root> 
</mx:XML>
 
  <mx:Script>
   <![CDATA[
    import mx.events.ListEvent;
    
    private function fnChange(e:ListEvent):void {
     var mXMLList:XMLList=tree1.dataProvider[0]..Pfolder.(@label==e.target.text);  // 콤보박스의 문구와 같은 label있는 XML를 모두 얻어낸다.
     
     if(0==mXMLList.length()){return;}
       
     tree1.expandChildrenOf( tree1.dataProvider[0], false ); // 전체 Item를 모두 닫는다.
     tree1.expandItem(mXMLList[0],true,true);// 선택된 Item를 열어준다.
    
   
     var mTempItem:XML=mXMLList.parent();   // 선택된 Item의 위쪽 Item를 모두 열어준다.
      while(null!=mTempItem){
          tree1.expandItem(mTempItem, true,true);
          mTempItem=mTempItem.parent();
      }
                    tree1.selectedItem=mXMLList[0]; // 선택 item를 조정한다.
      var idx:Number=tree1.getItemIndex( mXMLList[0]);  // 스크롤 위치를 조정한다.
      tree1.scrollToIndex(idx);
    }
    
   ]]>
  </mx:Script>   
     
<mx:Tree id="tree1" dataProvider="{xmlData}" showRoot="false" rowCount="6"  fontSize="12" labelField="@label"  width="294"  height="195"/>
<mx:ComboBox dataProvider="{xmlData..Pfolder}" labelField="@label" fontSize="12" change="fnChange(event)" />
</mx:Application>

Flex3.0&AS3 2008. 10. 23. 18:01

Tree Component



<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Style>
ToolTip
{
 fontSize:12;
}
</mx:Style>
<mx:XML id="xmlData">
<root> 
            <folder label="Stock" isBranch="true"> 
            </folder>             
            <folder label="Entertainment" isBranch="true">
                  <folder label="지상파 방송" isBranch="true" />
                  <folder label="케이블 방송" isBranch="true">
                          <Pfolder label="인천" />
                          <Pfolder label="수원" />
                  </folder>
            </folder>
           
            <folder label="Sports">
                  <Pfolder label="야구" />
                  <Pfolder label="축구" />
                  <Pfolder label="농구" />
                  <Pfolder label="배구" />
            </folder>
</root> 
</mx:XML>  
     
<mx:Tree id="tree1" itemRenderer="comp.TreeRenderer" dataProvider="{xmlData}" showRoot="false" rowCount="6"  fontSize="12" labelField="@label"  width="294" />
<mx:Label text="{tree1.selectedItem.toXMLString()}" fontSize="12" width="338" height="154"/>
</mx:Application>


TreeRenderer.mxml
<?xml version="1.0"?>
<local:TreeItemRenderer  xmlns:local="mx.controls.treeClasses.*" xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Script>
 <![CDATA[ 
        import mx.controls.treeClasses.*;
        import mx.collections.*;
       
        override public function set data(value:Object):void{
            super.data = value;
            if(!TreeListData(super.listData).hasChildren){return;}
           
            setStyle("color", 0xff0000);       // Branch이면 적색으로
            setStyle("fontWeight", 'bold');    // Branch이면 볼드로
        }
         
        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
            super.updateDisplayList(unscaledWidth, unscaledHeight);
            if(!super.data){ return;}
           
            icon.filters=[new  GlowFilter, new BlurFilter];                 // 폴더 아이콘에 Glow 효과
            disclosureIcon.filters=[new BlurFilter];          // 폴더열기닫기 Blue 효과
            super.label.toolTip = label.text;             // 툴팁 설정하기

            if(! TreeListData(super.listData).hasChildren){return;}           

            var tmp:XMLList =  new XMLList(TreeListData(super.listData).item);
            var myStr:int = tmp[0].children().length();
            super.label.text =  TreeListData(super.listData).label + "(" + myStr + ")";  // Branch에 대해서만 갯수를 표시한다.
        }

 ]]>
</mx:Script>
</local:TreeItemRenderer>

Flex3.0&AS3 2008. 10. 22. 18:19

사용자정의 ToolTip 구현하기 및 List 콤포넌트 Control


PanelToolTip.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
 width="250" fontSize="12" alpha=".8" borderThickness="2" backgroundColor="#dedede"
 borderColor="black" borderStyle="solid" implements="mx.core.IToolTip">
 <mx:Script>
  <![CDATA[
   private var _text:String;
   
   public function get text():String{
    return _text;
   }
   
   public function set text(value:String):void{
    _text=value;
   }
   
  ]]>
 </mx:Script>
 <mx:Text text="{_text}" percentWidth="100" width="198" height="22" fontSize="12"/>
</mx:Panel>

listBaseEx.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
 <mx:Script>
  <![CDATA[
   import comp.PanelToolTip;
   import mx.events.ToolTipEvent;
   import mx.events.ListEvent;
   import mx.controls.Alert;
   import mx.collections.IList;
   import mx.managers.DragManager;
   import mx.events.DragEvent;
   
   
   [Bindable]
    [Embed(source='imgs/rss.png')]
    private var m1:Class;
    
    private var mTipString:String;
    
    private function AppendData():void{
     var mNum:Number=dpd.length+1;
     dpd.addItem({label:"label"+mNum,data:"data"+mNum,icon:m1});
     
    }
    
    private function fnDragDrop(event:DragEvent):void{
     if(DragManager.COPY!=event.action)
     {
      return;
     }
     event.preventDefault();
     
     /*Drag한 아이템을 얻어옴*/
     var items:Array = event.dragSource.dataForFormat("items") as Array;
     
     var dropTarget:List = List(event.currentTarget);
     var dropLoc:int = dropTarget.calculateDropIndex(event); // 생성될 위치 얻어오기
     Alert.show(dropLoc.toString());
     
     for(var i:int=items.length -1 ; i>=0; i--){
      var tempItem:Object = {label:items[i].label, data:items[i].data, icon:items[i].icon};
      IList(dropTarget.dataProvider).addItemAt(tempItem,dropLoc);
     }
    }
    
     private function fnRollOut(event:ListEvent):void{
      mTipString = "";
      removeEventListener(ToolTipEvent.TOOL_TIP_CREATE, createCustomTip);
      
     }
     
     private function fnRollOver(event:ListEvent):void{
      event.target.addEventListener(ToolTipEvent.TOOL_TIP_CREATE,createCustomTip);
      
      mTipString = event.itemRenderer.data.toolTip; //툴팁 문구를 변수에 저장.
      event.target.toolTip = mTipString;
     }
     
     private function createCustomTip(event:ToolTipEvent):void{
      var ptt:PanelToolTip = new PanelToolTip();
      ptt.title = "Custom ToolTip";
      ptt.text = mTipString;
      event.toolTip = ptt;
     }
  ]]>
 </mx:Script>
 <mx:ArrayCollection id="dpd">
  <mx:source>
   <mx:Object label="label1" data="data1" icon="{m1}" toolTip="{lData.selectedItem.label}"/>
   <mx:Object label="label2" data="data2" icon="{m1}" toolTip="{lData.selectedItem.label}"/>
   <mx:Object label="label3" data="data3" icon="{m1}" toolTip="OK?"/>
  </mx:source>
 </mx:ArrayCollection>
 
 <mx:List id="lData" dataProvider="{dpd}" width="240" height="200" dragEnabled="true"
  dropEnabled="true" dragMoveEnabled="true" dragDrop="fnDragDrop(event)"
  itemRollOut="fnRollOut(event)" itemRollOver="fnRollOver(event)"
  />
 <mx:Label text="Selected label : {lData.selectedItem.label}"/>
 <mx:Label text="Selected data : {lData.selectedItem.data}"/>
 <mx:Image source="{lData.selectedItem.icon}"/>
 <mx:Button label="AppendData" width="195" click="AppendData()"/>
</mx:Application>


Flex3.0&AS3 2008. 10. 1. 17:16

flex_popup 띄우기

/*팝업띄우기*/

<mx:Script>
   <![CDATA[
    import mx.managers.PopUpManager; //팝업메니져
    import comp.popup.lessonMngPopup; //팝업대상
    
     public function showPopup(e:MouseEvent):void{
        var popup:* = lessonMngPopup(PopUpManager.createPopUp(this, lessonMngPopup, true )); 
        popup.owner = this;
     }
   ]]>
  </mx:Script>

/*팝업 센터 위치시키기*/
<mx:Script>
   <![CDATA[
    import mx.containers.TitleWindow;
    import mx.managers.PopUpManager;
     private function lessonSch():void{  
     var popWindow:TitleWindow=TitleWindow(PopUpManager.createPopUp(this,progEduLessonMngSch, true));     
     PopUpManager.centerPopUp(popWindow); 
     }
   ]]>
  </mx:Script>
위의 방법은 약간의 버그로 인해서 아래처럼 사용하는것을 추천

   var popupWindow:Object = PopUpManager.createPopUp( this, centerAdminSetSubmit, true );
   popupWindow.x = ( parentApplication.width - popupWindow.width ) / 2;
   popupWindow.y = ( parentApplication.height - popupWindow.height ) / 2;




/*팝업 닫기*/
<mx:Script>
   <![CDATA[
    import mx.managers.PopUpManager;
    import mx.events.ModuleEvent;
     private function closePopup(e:MouseEvent):void{
      PopUpManager.removePopUp(this);
     }
   ]]> 
  </mx:Script>
Flex3.0&AS3 2008. 10. 1. 14:57

= 액션스크립트[ActionScript] 3.0 XML =

= 액션스크립트[ActionScript] 3.0 XML =

var xml:XML = <root/>;

위와 같은 간단한 XML이 있습니다..
<root>에 <node>를 4개 추가하려면 xml.appendChild(<node/>);를 네번 써주면 되겠죠?
1000개라면 어떻게 할까요? 각자 다른 값을 가져야 한다면요? = _ = 막막하죠..?
이럴때는 중괄호 연산자({})를 이용하면 쉽게 해결할 수 있습니다..

for(var i:int = 1; i < 5; i++){
 xml.appendChild(<node {"num"+i}={i+10}>{i}</node>);
}

trace(xml.toXMLString());
/*
  <root>
    <node num1="11">1</node>
    <node num2="12">2</node>
    <node num3="13">3</node>
    <node num4="14">4</node>
  </root>
*/

모두 다른 값을 가지는 노드가 4개 추가되었습니다..
저들의 속성을 모두 출력하려면 어떻게 할까요?


for(var i:int = 1; i < 5; i++){
 trace(xml.node["@num"+i]);
}
/*
 11
 12
 13
 14
*/

** 플래시에서 에러가 난다면 아래쪽 for문의 var i:int 를 i로 바꾸고 실행하세요..변수를 중복 정의하면 에러가 나거든요..

Flex3.0&AS3 2008. 9. 29. 13:26

focus setting


<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/09/23/setting-focus-in-flex-using-the-focus-manager/ -->
<mx:Application name="FocusManager_setFocus_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;

            private function submitButton_click(evt:MouseEvent):void {
                Alert.show(evt.currentTarget.label,
                            Object(focusManager.getFocus()).name);
            }

            private function resetButton_click(evt:MouseEvent):void {
                username.text = "";
                password.text = "";
                Alert.show(evt.currentTarget.label,
                            Object(focusManager.getFocus()).name);
            }
        ]]>
    </mx:Script>

    <mx:ApplicationControlBar dock="true">
        <mx:Button label="Set focus to Username"
                click="focusManager.setFocus(username);" />
        <mx:Button label="Set focus to Password"
                click="focusManager.setFocus(password);" />
    </mx:ApplicationControlBar>

    <mx:Form id="form"
            defaultButton="{submitButton}">
        <mx:FormItem label="Username:">
            <mx:TextInput id="username" />
        </mx:FormItem>
        <mx:FormItem label="Password:">
            <mx:TextInput id="password"
                    displayAsPassword="true" />
        </mx:FormItem>
        <mx:FormItem direction="horizontal"
                horizontalAlign="right"
                width="100%">
            <mx:Button id="submitButton"
                    label="Submit"
                    click="submitButton_click(event);" />
            <mx:Button id="resetButton"
                    label="Reset"
                    click="resetButton_click(event);" />
        </mx:FormItem>
    </mx:Form>

</mx:Application>