 |
| Loading External Text |
| Return to the Tutorials page |
| |
|
Goal: Load data from an external text document into a text field on the stage, after the data has fully loaded. Introduction to event listeners
and custom functions.
Imported classes: flash.display.Sprite, flash.text.TextField,
flash.text.TextFieldAutoSize, flash.net.URLRequest,
flash.net.URLLoader and flash.events.Event
Methods: TextField(), TextFieldAutoSize(),
addChild(), URLRequest(), URLLoader(),
load() and addEventListener()
Flash version: Flash 9 Professional
Download final version
The ActionScript 3.0 Foundation Elements can be found in the Members' Section.
In this tutorial we will create a text field to hold the data from an external text file. Loading the data is acccomplished through the
use of the URLRequest() and URLLoader() methods. The URLRequest is used to
locate the text file and the URLLoader loads the data into a display object, in this case, the text field.
Before the data from the text file can be loaded into the text field, the text file needs to be loaded in full. To identify when
the file is fully loaded, we will "listen" for an event by utilizing the addEventListener() method. The
event we are listening for is the completion of the text file load. When that event has completed, a custom function will run
that will place the data from the text file into the text field on the stage.
|
Open Flash 9 and select a new Flash file (ActionScript 3.0). Name it LoadExternalText and save it inside the FlasherAS3_PartI
folder. In the Document Class box of the Properties panel, type LoadExternalText and then save the changes.
Open a new ActionScript file, name it LoadExternalText and then save it inside the Code folder.
You now have twenty separate files on your computer:
In the FlasherAS3_PartI folder -
LineAndCurve.fla, Triangles.fla, RectanglesSquare.fla, CircleEllipse.fla, Sprites.fla, MovieClips.fla,
Filters.fla, InheritingClasses.fla, FormattedText.fla and LoadExternalText.fla.
In the Code subfolder -
LineCurve.as, Triangles.as, RectanglesSquare.as, CircleEllipse.as, Sprites.as, MovieClips.as, Filters.as,
InheritingClasses.as, FormattedText.as and LoadExternalText.as.
Keep both LoadExternalText files open as we will be working with both of them simultaneously.
|
Return to LoadExternalText.fla and set the Classpath to the Code subfolder inside the FlasherAS3_PartI folder. Save
your changes.
|
Return to FormattedText.as and type in the following code:
Line 01: package
Line 02: {
Line 03: public class LoadExternalText extends Sprite
Line 04: {
Line 05: public function LoadExternalText()
Line 06: {
Line 07: }
Line 08: }
Line 09: }
Save the changes.
|
This tutorial will require the Sprite, TextField,
TextFieldAutoSize, URLRequest,
URLLoader and Event classes so let's import them now.
Place your cursor at the end of line 2 and press Return/Enter.
On line 3 type: import flash.display.Sprite;
Press Return/Enter.
On line 4 type: import flash.text.TextField;
Press Return/Enter.
On line 5 type: import flash.text.TextFieldAutoSize;
Press Return/Enter.
On line 6 type: import flash.net.URLRequest;
Press Return/Enter.
On line 7 type: import flash.net.URLLoader;
Press Return/Enter.
On line 8 type: import flash.events.Event;
Press Return/Enter to add a blank line on line 9.
Place your cursor at the end of line 13 and press Return/Enter.
All of our external text code will be placed between the constructor function's opening & closing curly braces.
Save the changes. The set up is done; let's create some formatted text!
|
There are three steps required to place a text field on the stage.
- Declare a variable (myText), set the data type to TextField and then instantiate a new TextField.
- Using the text property, set the text content.
- Using the addChild() method, place the text field on the stage.
1.) Declare a variable, set the data type to TextField and then instantiate a new TextField.
As movies become more complex, you will find that variables may need to be accessible outside of the current class. To share a variable
with all files located within a package (in this case all the files located within subfolder Code), add the
internal keyword in front of the variable and declare the variable in the custom class instead
of the constructor function.
Place your cursor at the end of line 11 and presss Return/Enter.
Set the variable's scope to internal, declare the variable name (myText), set the data type
(TextField) and then instantiate a new TextField.
On line 12 type: internal var myText:TextField = new TextField;
Press Return/Enter to set line 13 as a blank line.
2.) Using the text property, set the text content.
Place your cursor on line 16.
On line 16 type: myText.text = "DATA FROM TEXT FILE GOES HERE";
3.) Using the addChild() method, place the text field on the stage.
Press Return/Enter.
On line 17 type: addChild(myText);
Your code should look like this: [ view code ]
Save the changes and then test the movie to see the sentence appear in the upper left-hand corner of the stage.
The text field isn't long enough to accomodate the text string so let's add the autoSize property to the
text field. Place your cursor at the end of line 16 and press Return/Enter.
On line 17 type: myText.autoSize = TextFieldAutoSize.LEFT;
Your code should look like this: [ view code ]
Save the changes, retest the movie and the text string now fits perfectly.
|
Now it's time to create the text document that will contain the text data that will be loaded into the myText text field. In
the FlasherAS3_PartI folder, create a new subfolder named TextFiles.
Then open your operating system's text editor (mac = TextEdit / pc = Notepad). Copy the text below and paste it into the text document.
Adobe Flash CS3 Professional software is the most advanced authoring environment for creating rich
interactive content including websites, online advertisements, instructional media, presentations,
games, and mobile device content.
Flash CS3 Professional offers nearly limitless opportunities to student designers and developers
who are interested in building careers using interactive design technology. Flash CS3 is a common
denominator that integrates with and supports a broad spectrum of emerging technologies, including
Ajax, 3D animation, online video, and open source development.
Save the text document in the TextFiles folder and name it message.txt.
|
We will use the URLRequest method to locate the text document message.txt. First we need to
declare the variable (locateTextFile), set the data type (URLRequest) and instantiate the new URLRequest. To
ensure that this variable can be referenced by any file in the package, place the internal keyword in
front of the variable.
Place your cursor on line 13.
On line 13 type: internal var locateTextFile:URLRequest = new URLRequest("TextFiles/message.txt");
Your code should look like this: [ view code ]
Note that inside the new URLRequest object, there is a URL target (TextFiles/message.txt) that tells Flash exactly where the
text document can be found.
Save the changes.
|
The URLLoader() method actually places the data into a display container (a URLLoader).
Declare the variable (textFileLoader), set the data type (URLLoader) and instantiate a new URLLoader. Give the
variable internal scope.
Place your cursor at the end of line 13 and press Return/Enter.
On line 14 type: internal var textFileLoader:URLLoader = new URLLoader;
Press Return/Enter to ensure a blank line on line 15.
The load() method is used to load or send data from a specific URL. We've already established the
URL on line 13 and we've created a container to load the text document into (see line 14). Now we need to physically
load the text file into the loader.
Place your cursor at the end of line 17 and press Return/Enter.
On line 18 type: textFileLoader.load(locateTextFile);
Your code should look like this: [ view code ]
The display container (textFileLoader) now contains the contents of the locateTextFile variable, which is message.txt.
Save the changes.
If we were to test the movie now there would be no visible change on the stage. Though message.txt is available, the data (or the
content inside it) still needs to be specifically called.
|
This text document is very small and will load quickly and easily; but later on, we may want to add a larger text document that would load a
great deal slower. It is important to make sure the text document is fully loaded before trying to "call" the data inside it. But how can we
possibly know the moment when the text document is fully loaded?
The addEventListener() method "listens" for a specific event. Once that event has passed, an action
is triggered. In this example, we want to determine when the event is complete (i.e. message.txt is fully loaded).
Place your cursor at the end of line 18 and press Return/Enter.
On line 19 type: textFileLoader.addEventListener(Event.COMPLETE, loadData);
Your code should look like this: [ view code ]
Save the changes.
The addEventListener() method is attached to the textFileLoader because this is where the text document
will be loaded (into the URLLoader named textFileLoader). The event listener is looking for an event which is represented by
Event.
What about the event?
We want to know when that event is completed. This is represented by the COMPLETE string constant.
When the event is completed an action is triggered and called by name. In this case the name of the action(s) is
called loadData, a name that was created for this specific action. Now you may be wondering where loadData is and what it does. It
is a custom function that we will create in the next step.
|
A function comprises a set of statements that list the action(s) to be carried out.
A function looks like this:
function functionName( ): return value
{
statement(s) go here
}
It begins with the function keyword and then the function name which can be anything you like
(i.e. variable name). The statement(s), or actions, are placed between the two curly brackets.
NOTE:
Some functions can return a value. This is a more advanced skill which will not be covered within this series of tutorials. Therefore all
custom functions we create will have a return value of void.
The LoadExternalText.as file already contains a function; the constructor function that begins on line 16 and ends on
line 23. The constructor function is required in all AS files. It automatically runs as soon as the movie plays.
This new function will ultimately load the contents of message.txt into the myText text field on the stage. This
function should only run (be triggered) when the text document is fully loaded.
Now, if we placed our new function inside the constructor function, it would automatically run as soon as the movie played. However, if the
new function is placed within the main class, but outside of the constructor function, it will wait patiently until it is called.
Let's start with a test example. Initially, we will place a trace statement to see how the Event Listener works
in conjunction with this function. When the data is fully loaded, the sentence file is now loaded will appear in the
Output Window.
Place your cursor at the end of line 23 and press Return/Enter twice. Beginning on line 25, type the following:
Line 25: function loadData(event:Event):void
Line 26: {
Line 27: trace("file is now loaded");
Line 28: }
Your code should look like this: [ view code ]
Line 25: function loadData(event:Event):void
- The keyword function declares that the following is a function.
- loadData is the name of the function we created.
- The loadData function was called into being by an event represented by the
keyword event.
- That event is an Event datatype.
- The return value is void.
Line 26: {
The function begins.
Line 27: trace("file is now loaded");
The action is to trace the string file is now loaded into the Output Window.
Line 28: }
The function ends.
Save the changes and then test the movie.
Two things happen; first the Output Window appears. It contains the string
file is now loaded. This appeared when the text document was fully loaded. We listened for the loading event to be completed on
line 20. Once the event had passed, the loadData function was instructed to run.
Secondly, the text string DATA FROM TEXT FILE GOES HERE appears on the stage. This is because we filled the myText text field
with that string content (see line 18).
The loadData function contained an action. That action was to place the file is now loaded string into the
Output Window. Now the only thing left to do is to change the action in the loadData function. Instead of running a test message,
let's place the contents of message.txt inside the myText text field.
Save the changes.
|
|
The moment of truth! Now it is time to finally load the text content from message.txt into the myText text field. First let's
remove the text on line 20.
Delete the following from line 20: myText.text = "DATA FROM TEXT FILE GOES HERE";
This was merely a place holder for this tutorial to show where the text would appear on the stage.
Return to line 26 and replace the trace statement with the following:
On line 26 type: myText.text = event.target.data;
Your code should look like this: [ view code ]
This sets the text value of myText; event refers to our event listener (line 19),
target refers to the display object (textFileLoader also mentioned on line 19), and
data refers to the contents of the target. Here is the logic behind it...
- The contents of the target are defined. (The external file is created)
- The target is textFileLoader, a URLLoader.
- The loader contains a URLRequest named locateTextFile.
- In turn, locateTextFile contains a URL.
- That URL is TextFiles/message.txt, the location of the external file.
Save the changes, test the movie and you will see the two paragraphs describing 'Adobe Flash CS3 Professional software' on the stage.
|
First, take a moment to pat yourself on the back. You just made text, from a document located in a whole other folder, appear on the stage of the
movie. Well done!
There is a way we could improve the way the text flows. The text is left-aligned as we specified but the right margin isn't even
visible on the stage! What we need to add is the wordWrap property of the TextField class. This property is a
Boolean and will automatically wrap the text to fit the text field parameters.
Place your cursor at the end of line 19 and press Return/Enter.
On line 20 type: myText.wordWrap = true;
Your code should look like this: [ view code ]
Save the changes and test the movie.
Hmmm...the text does wrap but it still doesn't look quite right. The text field's default width is too small. Let's set the width to
the specific value of 500, which is the width of our movie.
The autoSize code on line 21 is no longer useful so it can be deleted. (It can not span more than one line.) Replace it with the following
code.
On line 21 type: myText.width = 500;
Your code should look like this: [ view code ]
Save the changes and test the movie. The text wraps around to the line below once it reaches the end of the text field's width
(500 px).
The final step is to change the default height of the text field to 200. Place your cursor at the end of line 21 and press
Return/Enter.
On line 22 type: myText.height = 200;
Your code should look like this: [ view code ]
Save the changes and test the movie. That's done the trick! All the text is visible and wraps beautifully down the stage.
There are a number of properties that can affect how text looks on the stage. Visit the TextField class section of the
ActionScript help files to discover additional properties to play with!
|
To recap, here are the steps to load the content of an external text document:
- Create a Text Field
- Create a URLRequest (location of file)
- Create a URLLoader (display object to hold the external file)
- Use the load() method to place the URLRequest inside the URLLoader.
- Add an Event Listener that will run a custom function once the external file is fully loaded.
- Create a custom function that will load the contents of the external file into the Text Field.
This tutorial covered several new elements. Event listeners and custom functions are key elements to creating complex and interactive Flash
movies. In future tutorials we will use these to animate objects and create interactive buttons.
However before we move on from the subject of Text, let's learn how to apply HTML formatting and create hyperlinks within a text field!
[ HTML Text & Hyperlinks tutorial ]
|
|
| |
|
 |
 |