views:

1289

answers:

2

Hi All, I am simply trying to draw a rectangle inside of a panel using flex4. I am using spark instead of mx. It complains about addchild being replaced by addelement; however, addelement expects type ivisualcomponent. I think sprite should be of that type; however, it reports an error when trying to use the below code... I have tried a few different ways. I think I am missing something very basic about flex 4. Any enlightenment would be much appreciated! :-D

private function drawRectangle(e:MouseEvent):void{
    var s:Sprite = new Sprite();
    s.graphics.beginFill(0x00ff00, 0.5);
    s.graphics.drawRect(e.localX,e.localY,50,50);
    s.graphics.endFill();
    canvas.addChild(s);
}
+3  A: 

Sprite doesn't implement IVisualComponent. (Check the docs: http://www.eonflex.com/flex/4.1/langref/flash/display/Sprite.html)

You need to add a UIComponent to hold the sprite. Something like:

private function drawRectangle(e:MouseEvent) : void {
    var s:Sprite = new Sprite();
    var c:UIComponent = new UIComponent();

    c.addChild(s);
    canvas.addChild(c);
}
ablerman
it needs to be addElement, but it worked :)
Parris
A: 

Note that you can also do this with MXML graphics:

<?xml version="1.0" encoding="utf-8"?>
<!-- fxg/GraphicCompMainMXML.mxml -->
<s:Application backgroundColor="0xFFFFFF"      
    xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:mx="library://ns.adobe.com/flex/mx" 
    xmlns:s="library://ns.adobe.com/flex/spark">
    <s:Graphic>    
         <s:Rect id="rect1" width="200" height="200">
              <s:fill>
                 <s:SolidColor color="0xFFFFCC"/>
              </s:fill>
              <s:stroke>
                 <s:SolidColorStroke color="0x660099" weight="2"/>
              </s:stroke>
         </s:Rect>
    </s:Graphic>
</s:Application>
matt horn