RangeError: Error #2006: The supplied index is out of bounds.
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) { // uncomment both removeChild() calls to prevent the error // alice.removeChild(aButton); bob.addChild(aButton); } else { // uncomment both removeChild() calls to prevent the error // bob.removeChild(aButton); 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.
Comments
Posted by: Case | August 9, 2007 4:15 PM
Posted by: Chetan Sachdev | January 16, 2008 2:32 AM
Posted by: Diego | April 30, 2008 9:11 AM
Posted by: pixum | October 13, 2008 7:30 PM
Posted by: Anonymous | December 29, 2008 4:43 PM
Posted by: Nishant | April 24, 2009 1:57 AM
Posted by: sun | December 31, 2009 3:13 AM
Posted by: Handipa | March 8, 2011 12:54 AM