2
votes

I have very basic question about Flex SDK, but I didn't find any resources for my problem and honestly don't know if it even possible to do what I want. So here is my question:

I created Flex project with Adobe Flex Builder 4.6. Then I placed the button (let's say it's id is btn1) in main MXML file. I want to create second button dynamically right from the script part of main MXML file. Specifically I want to create it from button click handler of btn1.

Here is my MXML code (it is the only file in project ):

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" 
               minWidth="955" minHeight="600">

    <fx:Script>
        <![CDATA[
            protected function btn1_clickHandler(event:MouseEvent):void
            {
                var btn2:Button = new Button();
                btn2.label = "Hello";
                btn2.x = 50;
                btn2.y = 50;
            }
        ]]>
    </fx:Script>


    <fx:Declarations>
        <!-- Non visual elements -->
    </fx:Declarations>

    <s:Button id="btn1" 
              x="10" y="10" 
              label="Кнопка"
              click="btn1_clickHandler(event)"/>

</s:Application>

But when I click btn1 - nothing happens. It is possible that I don't understand something in flex programming paradigm - please point it out for me.

1
addChild() that button, at the very least.Vesper
Don't use addChild(). Use addElement().Florent
@Florent oh thank you it works! How can I mark your comment as an answer to my question?GuardianX
@Florent Does Flex use addElement for any of its components, that are contained in spark or mx? I'm unfamiliar with Flex, while I have some experience with AS3.Vesper
If you decompile your SWF, you will understand how it works internally! Flex converts MXML files to AS3 and then uses addElement() to rebuild the MXML structure.Florent

1 Answers

2
votes

You have to add the button to the view using addElement().

var btn2:Button = new Button();
btn2.label = "Hello";
btn2.x = 50;
btn2.y = 50;

addElement(btn2);