A problem I've run across a couple of times when moving a component from one parent to another is the following error:
RangeError: Error #2006: The supplied index is out of bounds.
at flash.display::DisplayObjectContainer/getChildAt()
at mx.core::Container/getChildAt()
at mx.containers.utilityClasses::CanvasLayout/measure()
at mx.containers::Canvas/mx.containers:Canvas::measure()
(... some of stack trace deleted ...)
at mx.core::UIComponent/mx.core:UIComponent::callLaterDispatcher2()
at mx.core::UIComponent/mx.core:UIComponent::callLaterDispatcher()
at [renderEvent]
at [mouseEvent]
You'll notice that the stack trace is nothing but framework code. An error in a callLater that I didn't make? The problem is simple. When moving a component from one parent to another you have to call removeChild() on the current parent before calling addChild() to attach it to the new parent.
The following code demonstrates the issue:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
<mx:Script>
<![CDATA[
private var goToBob:Boolean = true;
private function swap():void
{
if (goToBob)
{
bob.addChild(aButton);
}
else
{
alice.addChild(aButton);
}
goToBob = !goToBob;
}
]]>
</mx:Script>
<mx:Label text="Clicking the Swap button twice will cause a RangeError: Error #2006"/>
<mx:Canvas id="alice">
<mx:Button id="aButton" label="Swap" click="swap();"/>
</mx:Canvas>
<mx:Canvas id="bob">
</mx:Canvas>
</mx:Application>
As noted in the code comments, if you first call removeChild() the error goes away. While it would be nice if the framework let to just move a component in a single step, I seem to remember seeing in the documentation that the need to call remove before add is explained.