9 Replies Latest reply on Feb 12, 2010 4:27 AM by Sherwette.Mansour

    Drag and Drop Image

    Sherwette.Mansour Level 1

      Hi,

      I am trying to drag and drop and image from a datagrid list component to a canvas, however, when I drop, it disappears! I need it to be copied in the canvas and can be dragged anytime in the canvas.

       

       

      Here is my code

       

      <?xml version="1.0" encoding="utf-8"?>

      <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"

      name="Drag and Drop Tutorial"

      creationComplete="init()"

      initialize="pictureService.send()">

       

      <mx:Script>

      <![CDATA[

      import mx.controls.Image;

      import mx.core.DragSource;

         import mx.core.IUIComponent;

         import mx.managers.DragManager;

         import mx.events.DragEvent;

         import mx.controls.Alert;

        

         import mx.rpc.events.FaultEvent;

      import mx.rpc.events.ResultEvent;

      import mx.collections.ArrayCollection;

       

      [Bindable] private var pictureData:ArrayCollection;

                  private function resultHandler(event:ResultEvent):void{

                  pictureData = event.result.data.image;

                  }

                  private function faultHandler(event:FaultEvent):void{

                  //code

                  }

       

      public function init():void

               {

                  // a mouseDown event will start the drag

              

            list.dataProvider = pictureData;

           

            //picture in the list is being dragged

             this.picture.addEventListener( MouseEvent.MOUSE_DOWN, beginDrag );

             // accepting a drag/drop operation...

           this.area.addEventListener( DragEvent.DRAG_ENTER, acceptDrop );

           // handling the drop...

            this.area.addEventListener( DragEvent.DRAG_DROP, handleDrop );

               }

              

               public function beginDrag( mouseEvent:MouseEvent ):void

      {

           // the drag initiator is the object being dragged (target of the mouse event)

             var dragInitiator:IUIComponent = mouseEvent.currentTarget as IUIComponent;

           

            // the drag source contains data about what's being dragged

            var dragSource:DragSource = new DragSource();

           

            // / Add the data to the object.

       

                      dragSource.addData(1, 'value');

                     /*  dragSource.addData(dragInitiator, "items"); */

       

       

                      // Create a copy of the coin image to use as a drag proxy.

                     var dragProxy:Image = new Image();

                      dragProxy.source = mouseEvent.currentTarget.source;

                      dragProxy.setActualSize(mouseEvent.currentTarget.width,mouseEvent.currentTarget.height)

            

           

           

           

           

           

            // ask the DragManger to begin the drag

            DragManager.doDrag( dragInitiator, dragSource, mouseEvent, dragProxy ); 

           

      }

       

      public function acceptDrop( dragEvent:DragEvent ):void

         {

             var dropTarget:IUIComponent = dragEvent.currentTarget as IUIComponent;

       

            // accept the drop

            DragManager.acceptDragDrop( dropTarget );

            // show feedback

            DragManager.showFeedback( DragManager.COPY );

           

           

           

           

              if(dragEvent.dragSource.hasFormat("items"))

        {

         var items:Array = dragEvent.dragSource.dataForFormat("items") as Array;

       

         trace(items[0].src);

         var img:Image = new Image()

         img.x=dragEvent.localX

         img.y=dragEvent.localY

         img.source=items[0].src

         img.addEventListener(MouseEvent.MOUSE_MOVE,beginDrag);

         area.addChild(img);

         }

         else

         {

        

         //makes an object moves

         dragEvent.dragInitiator.x=dragEvent.localX

         dragEvent.dragInitiator.y=dragEvent.localY

         } 

           

          }

        

           public function handleDrop( dragEvent:DragEvent ):void

         {

            var dragInitiator:IUIComponent = dragEvent.dragInitiator;

            var dropTarget:IUIComponent = dragEvent.currentTarget as IUIComponent;

         

           

           

         }

       

         public var xOff:Number;

                  public var yOff:Number;

       

        

       

        

      ]]>

      </mx:Script>

       

       

       

         <mx:HTTPService id="pictureService"

      url="data/data.xml"

      result="resultHandler(event)"

      fault="faultHandler(event)"/>

       

      <mx:DataGrid id="list" width="238" height="200" y="26" x="10" labelField="src" dragEnabled="true"

      dataProvider="{pictureData}">

        <mx:columns>

       

        <mx:DataGridColumn dataField="id" id="code">

       

        </mx:DataGridColumn>

        <mx:DataGridColumn id="picture" draggable="true" >

        <mx:itemRenderer>

        <mx:Component>

        <mx:Image source="assets/{data.id}.jpg"  />

       

        </mx:Component>

        </mx:itemRenderer>

        </mx:DataGridColumn>

       

      </mx:columns>

      </mx:DataGrid>

      <mx:Canvas id="area" x="266" y="28" width="436" height="401" backgroundColor="#c0c0c0"

      dragDrop="handleDrop(event)" >

      </mx:Canvas>

       

      </mx:Application>

       

       

      I'd really appreciate your help in this.

      Thanks

        • 1. Re: Drag and Drop Image
          Flex harUI Adobe Employee

          I would expect handleDrop to create an instance of something and call

          addChild()

          • 2. Re: Drag and Drop Image
            Sherwette.Mansour Level 1

            I have added this code to HandleDrop, but it still disappears.

             

            public function handleDrop( dragEvent:DragEvent ):void

               {

                  var dragInitiator:IUIComponent = dragEvent.dragInitiator;

                  var dropTarget:IUIComponent = dragEvent.currentTarget as IUIComponent;

                 

                  var newImage:Image = new Image();

                  var dropCanvas:Canvas = dragEvent.currentTarget as Canvas;

                  dropCanvas.addChild(newImage);

             

               

               }

             

             

            The application is attached.

             

            Thanks for the reply

            Sherwette

            • 3. Re: Drag and Drop Image
              Gregory Lafrance Level 6

              If this post answers your question or helps, please mark it as such.


              Greg Lafrance - Flex 2 and 3 ACE certified

              www.ChikaraDev.com

              Flex / AIR Development, Training, and Support Services
              ------------------------------------------------------------------------------------------ --------------------------------------

              The following code works. Notice the following in my code:

               

              I add the MouseDown event handler to the Image item renderer, because if you add it to the datagrid column, well it does not have a source property, or at least it is not the dragged image, so that won't work.

               

              Also notice I ripped som code out of your acceptDrop function and put it in the handleDrop function where it should be.

               

              I also don't know why you were expecting the data in the dataSource to be an array. Its just the source of the dragged image, so its just a string.

               

              I also set the width and height of the image to add.

               

              So your code was a little confusing, but like I said, it works (10 points please ).

               

               

              <?xml version="1.0" encoding="utf-8"?>
              <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
                layout="vertical" name="Drag and Drop Tutorial" 
                creationComplete="init()" initialize="pictureService.send()">
                <mx:Script>
                  <![CDATA[
                    import mx.controls.Image;
                    import mx.core.DragSource;
                    import mx.core.IUIComponent;
                    import mx.managers.DragManager;
                    import mx.events.DragEvent;
                    import mx.controls.Alert;
                    
                    import mx.rpc.events.FaultEvent;
                    import mx.rpc.events.ResultEvent;
                    import mx.collections.ArrayCollection;
                    
                    [Bindable] private var pictureData:ArrayCollection;
                    private function resultHandler(event:ResultEvent):void{
                      pictureData = event.result.data.image;
                    }
                    private function faultHandler(event:FaultEvent):void{
                      //code
                    }
                    
                    public function init():void{
                      // a mouseDown event will start the drag      
                      list.dataProvider = pictureData;
                    
                      // accepting a drag/drop operation...
                      this.area.addEventListener( DragEvent.DRAG_ENTER, acceptDrop );
                      // handling the drop...
                      this.area.addEventListener( DragEvent.DRAG_DROP, handleDrop ); 
                    }
                    
                    public function beginDrag( mouseEvent:MouseEvent ):void{
                      // the drag initiator is the object being dragged (target of the mouse event)
                      var dragInitiator:IUIComponent = mouseEvent.currentTarget as IUIComponent;
                    
                      // the drag source contains data about what's being dragged
                      var dragSource:DragSource = new DragSource();
                      // / Add the data to the object.      
                      //dragSource.addData(1, 'value'); 
                      dragSource.addData(mouseEvent.currentTarget.source, "items");
                                
                      // Create a copy of the coin image to use as a drag proxy.
                      var dragProxy:Image = new Image();
                      dragProxy.source = mouseEvent.currentTarget.source;
                      dragProxy.setActualSize(mouseEvent.currentTarget.width,mouseEvent.currentTarget.height)
                    
                      // ask the DragManger to begin the drag
                      DragManager.doDrag( dragInitiator, dragSource, mouseEvent, dragProxy );        
                    }
                    
                    public function acceptDrop( dragEvent:DragEvent ):void{
                      if (dragEvent.dragSource.hasFormat("items")){
                        DragManager.showFeedback( DragManager.COPY ); 
                        DragManager.acceptDragDrop(Canvas(dragEvent.currentTarget));
                      }
                    } 
                    
                    public function handleDrop( dragEvent:DragEvent ):void{
                      var dragInitiator:IUIComponent = dragEvent.dragInitiator;
                      var dropTarget:IUIComponent = dragEvent.currentTarget as IUIComponent;
                      
                      var items:String = dragEvent.dragSource.dataForFormat("items") as String;
                      var img:Image = new Image();
                      img.x=dragEvent.localX;
                      img.y=dragEvent.localY;
                      img.width = 50;
                      img.height=50;
                      img.source=items.toString();
                      img.addEventListener(MouseEvent.MOUSE_MOVE,beginDrag);
                      area.addChild(img);
                    }      
                    public var xOff:Number;
                    public var yOff:Number;
                  ]]>
                </mx:Script>
                <mx:HTTPService id="pictureService" url="data/data.xml"
                  result="resultHandler(event)" fault="faultHandler(event)"/>
                <mx:DataGrid id="list" width="238" height="200" y="26" x="10" labelField="src" 
                  dragEnabled="true" dataProvider="{pictureData}">
                  <mx:columns>
                    <mx:DataGridColumn dataField="id" id="code"/>
                    <mx:DataGridColumn id="picture" draggable="true" >
                      <mx:itemRenderer>
                        <mx:Component>
                          <mx:Image source="assets/{data.id}.png" mouseDown="outerDocument.beginDrag(event)"/>
                        </mx:Component>
                      </mx:itemRenderer>
                    </mx:DataGridColumn>
                  </mx:columns>
                </mx:DataGrid>
                <mx:Canvas id="area" width="436" height="401" 
                  backgroundColor="#c0c0c0" dragDrop="handleDrop(event)" >
                </mx:Canvas> 
              </mx:Application>
              
              
              1 person found this helpful
              • 4. Re: Drag and Drop Image
                Sherwette.Mansour Level 1

                Thank you Thank you for your assistance in my matter.

                 

                I have tried to follow your adjustments to the code, though there is no compile error, there is runtime error as follows:

                 

                TypeError: Error #1009: Cannot access a property or method of a null object reference.

                at DragDropHopeTutorial4/handleDrop()[C:\Users\Shoushou\Documents\Flex Builder 3\DragDropHopeTutorial\src\DragDropHopeTutorial4.mxml:120]

                at DragDropHopeTutorial4/__area_dragDrop()[C:\Users\Shoushou\Documents\Flex Builder 3\DragDropHopeTutorial\src\DragDropHopeTutorial4.mxml:162]

                at flash.events::EventDispatcher/dispatchEventFunction()

                at flash.events::EventDispatcher/dispatchEvent()

                at mx.core::UIComponent/dispatchEvent()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\co re\UIComponent.as:9051]

                at mx.managers.dragClasses::DragProxy/mouseUpHandler()[E:\dev\3.0.x\frameworks\projects\fram ework\src\mx\managers\dragClasses\DragProxy.as:500]

                line 120: img.source=items.toString();
                inside handleDrop function
                and
                line162: <mx:Canvas id="area" x="266" y="28" width="436" height="401" backgroundColor="#c0c0c0"
                dragDrop="handleDrop(event)" >
                I know my code is a little confusing, because I am just a beginner and I use the internet as my reference. So, please if you know any advanced tutorials for flex online, please advice me.
                Thank you

                • 5. Re: Drag and Drop Image
                  Sherwette.Mansour Level 1

                  I have tried to debug the code, and i narrowed it down to this line.

                   

                  img.source=items.toString();

                   

                  in the handleDrop function, apparently there is a problem with the source and string, but I can't figure it out. Please I really appreciate your help in this.

                  Thank you

                  • 6. Re: Drag and Drop Image
                    Flex harUI Adobe Employee

                    Items is an array.  Try items[0].toString(), but it really matters what

                    items[0] is and what field you want to pull.

                    • 7. Re: Drag and Drop Image
                      Sherwette.Mansour Level 1

                      I changed items to a type of Object.

                       

                      var items:Object = dragEvent.dragSource.dataForFormat("items") ;

                       

                      Now, when its dropped, it shows an unavailable image.

                      • 8. Re: Drag and Drop Image
                        Flex harUI Adobe Employee

                        Items is an Array, not an object.  Try something like this:

                         

                              public function handleDrop( dragEvent:DragEvent ):void{

                                var dragInitiator:IUIComponent = dragEvent.dragInitiator;

                                var dropTarget:IUIComponent = dragEvent.currentTarget as

                        IUIComponent;

                                 

                                var items:Array = dragEvent.dragSource.dataForFormat("items") as

                        Array;

                                var img:Image = new Image();

                                img.x=dragEvent.localX;

                                img.y=dragEvent.localY;

                                img.width = 50;

                                img.height=50;

                                img.source="assets/" + items[0].id + ".png";

                                img.addEventListener(MouseEvent.MOUSE_MOVE,beginDrag);

                                area.addChild(img);

                        • 9. Re: Drag and Drop Image
                          Sherwette.Mansour Level 1

                          It worked! Thank you very much