Refer to text field by class instance name
I need to populate the text field tField
开发者_StackOverflow社区 (defined on stage) that resides inside ParentClass
(MovieClip with same class name). I want to be able to set tField.text
to whatever I want from AnotherClass
. How do I do it?
Use getChildByName. First you create the TextField
in a class.
import flash.display.TextField;
var tField:TextField = new TextField();
tField.name = "tField";
stage.addChild(tField);
Note that you need to set the name. In another class, you can use:
var tField:TextField = stage.getChildByName("tField");
trace(tField.name); // tField
Changed answer to full instructions because the asker is probably missing a key step through the Flash GUI.
- Open Adobe Flash CS5 (might work for CS4 too.)
- File, New, Actionscript 3.0.
- Click the text tool. Draw a TextField.
- Click the TextField, in the Properties window select Input Text in the drop down.
- With the TextField still selected, in the Properties window, set the Instance Name to "tField" no quotes.
- Click on the stage. In the Properties window set the Class: text field to "Main" no quotes.
- File, Save As, "Test.fla" no quotes.
- File, New, Actionscript 3.0 class.
Paste the following in to the new AS file:
package {
import flash.display.MovieClip; import flash.events.FullScreenEvent; import flash.events.MouseEvent; import flash.events.Event; public class Main extends MovieClip { public function Main() { var another:Another = new Another(this.tField); } }
}
File, Save As, "Main.as" no quotes, IN THE SAME DIRECTORY AS STEP 3.
- File, New, Actionscript 3.0 class.
Paste the following code into the new .as file (I can't get StackOverflow to display this correctly. Just paste it as is):
package { import flash.text.TextField; public class Another { public function Another(textField:TextField) { textField.text = "Hello"; } } }
File, Save As, "Another.as" no quotes, in the SAME DIRECTORY AS STEP 3.
- Hit Ctrl-Enter.
All drawing a TextField on the stage and setting its instance name does is secretly add the lines of code:
public var tField:TextField = new TextField();
tField.type = "input";
To whatever class the stage is associated with (in this case, the class Main.) If you need any more help than that, I would recommend getting a good book on AS3 programming and the Flash IDE because the answer is well beyond the scope of a simple StackOverflow answer.
精彩评论