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);