AS3 example Message Box

From EduTech Wiki
Jump to: navigation, search

Draft


1 Introduction

This example belongs to the AS3 Tutorials Novice and is part of our Actionscript 3 tutorial series.

You will learn how to create Text fields, i.e. boxes filled with text. We also will try to teach you how to find information in the official ActionScript 3.0 documentation.

2 Working Example

Copy and paste this code in a text file. Save that textfile as "MessageBox.as". The name of the file *must* be the same as the name of the main class.

 package  {

    import flash.display.Sprite;
    import flash.text.TextField;
 
    public class MessageBox extends Sprite {
    
        function MessageBox():void {

         var msgbox:Sprite = new Sprite();

          // drawing a white rectangle
          msgbox.graphics.beginFill(0xFFFFFF); // white
          msgbox.graphics.drawRect(0,0,300,20); // x, y, width, height
          msgbox.graphics.endFill();
 
          // drawing a black border
          msgbox.graphics.lineStyle(2, 0x000000, 100);  // line thickness, line color (black), line alpha or opacity
          msgbox.graphics.drawRect(0,0,300,20); // x, y, width, height
        
          var textfield:TextField = new TextField();
          textfield.text = "Hi there!";

          addChild(msgbox);
          addChild(textfield);
        }
     }
  }

3 Walkthrough

---

 package  {

Mandatory package declaration

---

    import flash.display.Sprite;
    import flash.text.TextField;

Import statements. For reasons of speed, it is not very efficient to provide any program with any possible functionality. The import construct is used to import all functionalities required for the program to run... and no more than what is required for the program to run.

We are already familiar with the Sprite object from the Drawing graphic example. A TextField object is very similar. It is specialized in the drawing of string type of data. Any TextField objects has a property called "text". Whenever a new value is given to the object's text variable, the content of the text field gets updated.

---

    public class MessageBox extends Sprite {

We need at least one class definition in our file. The class definition and the filename must be identical in every way (character case must match). We need to add extends Sprite to have the ability to add Sprite onto the screen. If you were to erase extends Sprite and try and compile your program, you would get an error message "Call to a possibly undefined method addChild."

---

        function MessageBox():void {

This is the class constructor. This bits gets executed whenever the class is being instantiated. When we run the file "MessageBox.swf", we ask to instantiate the class.

---

         var msgbox:Sprite = new Sprite();

We create a sprite object to hold the message box content, graphics and text.

---

          // drawing a white rectangle
          msgbox.graphics.beginFill(0xFFFFFF); // white
          msgbox.graphics.drawRect(0,0,300,20);
          msgbox.graphics.endFill();

          // drawing a black border
          msgbox.graphics.lineStyle(2, 0x000000, 100);  // line thickness, line color, line alpha or transparency
          msgbox.graphics.drawRect(0,0,300,20);

Draws a pretty box, with a white rectangle and a black border

---

          var textfield:TextField = new TextField();
          textfield.text = "Hi there!";

We need to add a textfield object for text to appear on the screen.

As we need access to the properties of TextField objects, make sure that the appropriate import statement has been added at the top of the file.

---

          addChild(msgbox);   
          addChild(textfield);

For the textfield and sprite content to appear on the screen, we need to explicitly add them to the display. ---

        }
     }
  }

Every parenthesis or bracket that has been opened needs to be closed

4 Variants

4.1 Color changes

Change the color of the rectangle. Color code information can be found on the page about Color Schemes and Color Codes

Change this line:

msgbox.graphics.beginFill(0xFFFFFF); // white

Into this:

msgbox.graphics.beginFill(0xFFF7CC); 

And you will have a pale yellow background, post-it style. Note that the color code string always starts with '0x' rather than '#' as is usual in html code. The first character, 0, is a zero and not an uppercase O.

If you type an uppercase O, you will get this error message: "Error: Access of undefined property OxFFFFFF."

4.2 Longer text

Change the text value. Try typing a very very long paragraph.

For instance, try this:

 textfield.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do 
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat 
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia 
deserunt mollit anim id est laborum";

(All in on one line; Lorem Ipsum is simply dummy text of the printing and typesetting industry)

What are the problems you notice? On my screen, I only get 3 words to appear: "Lorem ipsum dolor ".

Put the mouse pointer on the text, click and drag to select text, go to the right handside of the screen. You should see the text change, scrolling through the full paragraph. Clearly, all the text is there. It seems that the display area is limited to a small area.

Try this:

 textfield.width=300;   // 300 is the width of our message box rectangle. 
 textfield.text = "Lorem ipsum dolor ...";

Better, now the text fills the length of the message box. Still, the full paragraph doesn't appear.

What if we were to try to increase the height?

 textfield.width=300;
 textfield.height=100;

Still only one line of text. We are up for a challenge.

4.3 Different box size

Change the size of the rectangle. What is the problem that you encounter? How easy is it to keep the white background and black border in matching positions?

4.4 Different drawing orders

Rather than this:

          addChild(msgbox);   
          addChild(textfield);

Type:

          addChild(textfield);
          addChild(msgbox);   

What has become of the textfield? Where did it disappear?

4.5 Changing the position of the box

Replace these lines:

          addChild(msgbox);   
          addChild(textfield);

With these:

          msgbox.x = 50;
          msgbox.y = 50;
          addChild(msgbox);   
          addChild(textfield);

x and y are properties of the sprite object that store the current x and y position of the object on the screen. When a new value is assigned to the object's x or y, the position is being updated.

The text is completely out of the box. Why?

Try this:

          msgbox.addChild(textfield);
          msgbox.x = 50;
          msgbox.y = 50;
          addChild(msgbox);   

The text is now inside the message box. It will remain inside whatever value we give to x and y. Why?

5 Challenges

5.1 Showing a long text over multiple lines

Try adding \n in different places in your text. For instance, type this:

 textfield.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad\n
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea\n
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit\n
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat\n
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";

(should be typed as one line).

Let's say that you want to change the width of your recangle from 300 to 500. How annoying would it be to re-edit your text?

A better solution needs to be found.

The idea of the following is to get you to discover how to locate information that can help you realize what you want to achieve. Spend an absolute maximum of 5 minutes on each search (30 seconds is enough in most cases).

Go to Google, run a search on "actionscript 3" text. Do you find any link that seems to offer the information you need? Go to Adobe livedoc, type "text" in the search box on the topright of the page. Any link that seems to offer the information you need? Go to ActionScript 3.0 Language and Components Reference, type text in the search box on the top of the page. Better matches?

We used "import flash.text.TextField;" at the top of our page. Go back to the ActionScript 3.0 Language and Components Reference. At the topleft of the page, there is a box called "Packages". Scroll this box down until you locate a line "flash.text". Click on it. A list of classes should appear. Click on the "TextField" link. Better information?

Go back to the ActionScript 3.0 Language and Components Reference. At the bottom left of the page, there is a box called "All Classes". Scroll this box down until you locate a line "TextField". Click on it. Iis the information any different from the result obtained by looking at the flash.text package definition?

Based on the content of the page about the package flash.text and the one on the Class Textfield, what is the fundamental difference between the two? We will give a formal answer later. Go with your best guess.

5.2 A function to create the message box graphics

When experimenting with variants, we noticed that it was a bit tedious to have to modify the size values for both the background rectangle and the border rectangle. There is always the risk of updating one while forgetting to update the other. Of course, this is rapidly noticed. Still, you need to change the code, compile, check out the resulting .swf anytime you make an error. This causes some delays. Imagine if you had a screen full of such messagebox, all of different dimensions!

How could you make it easier to update the size of the rectangle box (background and border)?

Read the page on AS3 Instances Functions. In view of the information presented there, how could you reorganize your code so that you the message box can be resized with a single command?

5.3 Box background drawn using the TexField properties and methods

We used a sprite object to draw a border around the text. A problem though is that this rectangle won't change of size is the text is to occupy a space larger than the width of the box.

How would you achieve the same effect using TextField objects built-in properties and functions?

Have a look at the TextField class documentation at adobe livedocs, You will notice that listed there are "public properties" and "public functions". Hint, run a search on the page (ctl-F) and look for the words "border", then the word "background", and perhaps the word "wordwrap".