在AS3中动态创建文本区域

时间:2011-07-20 08:36:08

标签: actionscript-3

我是AS3和Flex的新手。我想在点击或按钮上添加一个文本区域,例如,假设一个人有多个地址并且他们想要添加更多地址。当用户点击“添加地址”时,应该会出现一个新的文本区域。我已经到处寻找解决方案,但没有运气

听到我试过的代码(这可能是非常错误的):

import mx.controls.Alert;
import mx.events.CloseEvent;
private function createTextField(evt:Event):void{
    var theTextField:TextField = new TextField();
    theTextField.type = TextFieldType.INPUT;
    theTextField.border = true;
    theTextField.x = 10;
    theTextField.y = 10;
    theTextField.multiline = true;
    theTextField.wordWrap = true;
    addChild(theTextField);
}

<mx:FormItem>
<mx:Button label="Add Text Area" click="createTextField(event);"/>
</mx:FormItem>

提前感谢任何可以提供帮助的人。

2 个答案:

答案 0 :(得分:0)

你正在混合基于flash和基于flex的组件 - 因为你使用mxml我假设你正在使用flex。

mx命名空间是“旧的”(pre flex4组件) - 您可能希望使用spark-components,因此也就是s命名空间。

<s:Button />

如果要动态地向mxml添加组件,则不要使用addChild(作为/ flash)而是使用addElement()。最后,您不是创建基于Flash的TextField,而是创建基于flex的TextInput:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                   xmlns:s="library://ns.adobe.com/flex/spark" 
                   xmlns:mx="library://ns.adobe.com/flex/mx"
                   creationComplete="onCreationComplete(event);"
                   >
<fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>

    <fx:Script>
      <![CDATA[

        import spark.components.TextInput;

        private function onCreationComplete(evt:Event):void
        {
            trace("onCreationComplete()");
            var txt:TextInput = new TextInput();
            grp.addElement(txt);
        }

    ]]>
  </fx:Script>

  <s:VGroup id="grp">
  </s:VGroup>

</s:WindowedApplication>

答案 1 :(得分:0)

非常简单,请看下面的例子:

<?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"
               width="250" height="250">

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

    <fx:Script>
        <![CDATA[

        import flash.events.Event;
        import spark.components.TextArea;

        protected function onButtonClick(e:Event):void
        {
            var textArea:TextArea = new TextArea();
            textArea.id = "textArea";
            addElement(textArea);

        }// end function

        ]]>
    </fx:Script>

    <s:layout>
        <s:VerticalLayout></s:VerticalLayout>
    </s:layout>

    <s:Button id="button" click="onButtonClick(event)">Add Text Area</s:Button>

</s:Application>

只需使用Button属性向click元素添加事件侦听器即可。然后在事件处理程序中创建一个TextArea对象,并使用其addElement()方法将其添加到应用程序。

以下是正在运行的Flex应用程序的图像:

enter image description here

相关问题