2012-09-17 45 views
1

剛開始學習Flex。但是我對基本代碼感到興奮。我正在嘗試檢查如何通過操作腳本將組件(例如按鈕)添加到應用程序容器。但是我無法看到輸出中的按鈕。下面是我的代碼,使用動作腳本動態添加組件

<?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" 
      creationComplete="init()"> 
<fx:Script> 
    <![CDATA[ 

      import mx.controls.Alert; 

      import spark.components.Button; 
      import spark.layouts.BasicLayout; 

      private function init():void{ 
       var bl:BasicLayout = new BasicLayout(); 
       var app:Application = new Application(); 
       var button1:Button = new Button(); 
       var button2:Button = new Button(); 

       button1.label ="Button one"; 
       button1.x = 100; 
       button2.label = "Two"; 
       button2.x = 30; 
       layout = bl; 
       addChild(button1); 
       addChild(button2); 


      } 
    ]]> 
</fx:Script> 
<fx:Declarations> 
    <!-- Place non-visual elements (e.g., services, value objects) here --> 
</fx:Declarations> 

什麼是錯誤的,我在這裏做什麼?

感謝

+0

也許你應該告訴我們什麼不起作用? –

回答

4

此代碼甚至應該拋出運行時錯誤,因爲您不允許在此處使用addChild
由於Flex 4有一個新的組件集合(稱爲Spark)。向Spark容器添加視覺項目時,您必須使用addElement方法。而且由於s:Application是一個Spark容器,所以你也應該在這裏做。因此,只需在您的代碼中將addChild替換爲addElement即可。

您可能會問:如果我不能使用它,爲什麼「addChild」仍然存在?
那麼,答案是:遺產。所有Flex組件(即mx和Spark)均繼承自UIComponent,該組件實現了Flex框架的addChild方法(addChild實際上是DisplayObjectContainer類的純ActionScript方法)。 addElement做了一些額外的東西(我不會在這裏太技術),這就是爲什麼你不能再使用addChild。但是addChild仍然存在(繼承自UIComponent),並會拋出一個錯誤,告訴您不能使用此方法。

這是SkinnableComponent相關代碼:

override public function addChild(child:DisplayObject):DisplayObject 
{ 
    throw(new Error(resourceManager.getString("components", "addChildError"))); 
} 
+0

謝謝。你是對的。我在調試模式下檢查它,並明確表示使用addElement而不是addChild。但不知道爲什麼是這樣,現在就從你的答案中知道原因。 – droidsites

+0

值得一提的是,UIComponent'addChild()'方法在這一點上並不完全沒有用處。對於它的孩子來說是這樣。但是您可以使用UIComponent將Sprites或其子項添加到Flex UI,這是使用UIComponent子項所不可能的。 –

0

我不familar與將BasicLayout,但我認爲你可以看到按鈕,如果你保持代碼的簡潔:

private function init():void{ 
      // var bl:BasicLayout = new BasicLayout(); 
      // var app:Application = new Application(); 
// 1. Create button 
      var button1:Button = new Button(); 
      var button2:Button = new Button(); 
// 2. customize button 
      button1.label ="Button one"; 
      button1.x = 100; 
      button2.label = "Two"; 
      button2.x = 30; 
// 3. add button into the container, 'this' is Applciation 
      // layout = bl; 
      addElement(button1); // addChild for Flex3 
      addElement(button2); 
     } 

修改代碼,然後再試一次,祝你好運!

+0

與他的代碼有什麼不同? –