actionscript-3flashflash-cs5flash-cs6

ActionScript 3: Error #2025


My code works fine. It's suppose to bring in one image when the user presses 1 and swap it out for another when he / she presses 2. But, when I presses 1 or 2 after having previously pressing either the same number I get a #2025 error. Ex: Pressing 1 then pressing 1 again.

ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller. at flash.display::DisplayObjectContainer/removeChild() at warren_fla::MainTimeline/reportKeyDown2()

Code

import flash.events.KeyboardEvent;

var bdata = new image1(stage.stageWidth, stage.stageHeight);
var bdata2 = new image2(stage.stageWidth, stage.stageHeight);
var bmp = new Bitmap(bdata);
var bmp2 = new Bitmap(bdata2);

function reportKeyDown(event:KeyboardEvent):void 
{ 
if (event.keyCode == 49) {
    //trace("1 is pressed");
    bmp.x = 230;
    bmp.y = 150;
    addChild(bmp);
}
if (contains(bmp2)) {
    removeChild(bmp2);
    }
}

function reportKeyDown2(event:KeyboardEvent):void 
{ 
if (event.keyCode == 50) {
    //trace("2 is pressed");
    bmp2.x = 230;
    bmp2.y = 150;
    addChild(bmp2);
    removeChild(bmp);
}

} 

stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown2);

Solution

  • You are removing bmp without checking if it is already a child.

    function reportKeyDown2(event:KeyboardEvent):void 
    { 
        if (event.keyCode == 50) {
            //trace("2 is pressed");
            bmp2.x = 230;
            bmp2.y = 150;
            addChild(bmp2);
            if(contains(bmp)) 
                removeChild(bmp);
        }
    } 
    

    Also your code can be refactored into this simpler version :

    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;
    
    var bdata = new image1(stage.stageWidth, stage.stageHeight);
    var bdata2 = new image2(stage.stageWidth, stage.stageHeight);
    var bmp = new Bitmap(bdata);
    var bmp2 = new Bitmap(bdata2);
    
    function reportKeyDown(event:KeyboardEvent):void 
    { 
        if (event.keyCode == Keyboard.NUMBER_1) {
            swapBitmaps(bmp, bmp2);            
        } else if (event.keyCode == Keyboard.NUMBER_2) {
            swapBitmaps(bmp2, bmp);            
        }
    }
    
    function swapBitmaps(first:Bitmap, second:Bitmap):void
    {
          first.x = 230;
          first.y = 150;
          addChild(first);
          if(contains(second)) {        
               removeChild(second);
          }
    }
    
    stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);