GuardianX
GuardianX

Reputation: 512

Dynamically create button in Flex

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.

Upvotes: 2

Views: 2449

Answers (1)

Florent
Florent

Reputation: 12420

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

Upvotes: 2

Related Questions