actionscript-3flashapache-flexflash-builderflex-mx

Programmatically create grid in flex


I'm trying to learn flex right now and I'm having some troubles. I want to create a new grid but not in the XML. I want to create it in the script section.

This is the code I wrote:

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx"
           xmlns:flextras="http://www.flextras.com/mxml"
           width="1500" height="700">
    <fx:Declarations>
        <!-- Placer ici les éléments non visuels (services et objets de valeur, par exemple). -->
    </fx:Declarations>

    <fx:Script>
        <![CDATA[
            import flash.sampler.NewObjectSample;

            import mx.containers.Grid;
            import mx.containers.GridItem;
            import mx.containers.GridRow;

            import spark.components.Button;
            import spark.components.gridClasses.GridColumn;

            private var myGrid: Grid;
            private var gridRow : GridRow;
            private var gridItem : GridItem;
            private var myButton : Button;


            private function init():void
            {
                myGrid = new Grid();
                gridRow = new GridRow();
                gridItem = new GridItem();
                myButton = new Button();
                myButton.label = "Hi guys !";

                gridItem.addChild(myButton);
                gridRow.addChild(gridItem);
                myGrid.addChild(gridRow);
                myGrid.validateNow();
            }

        ]]>
    </fx:Script>

</mx:Canvas>

What have I done wrong?


Solution

  • You've added the item to the row and the row to the grid, but you haven't added the grid to the canvas

    this.addChild(myGrid);