Flex tutorial – Build a calculator

Flex

With Flex you can create applications. So, why not start creating a very simple application, like a calculator?

How does a calculator work, in my opinion? Simple: it just evaluates a string. But how can we evaluate a simple string like “1+1″ in AS3? I think we can’t, because eval() isn’t supported in actionscript 3. So I search on google, and found some solutions for it. But nothing really satisfied me. I don’t want to use PHP or another serverside script for evaluating strings, do you? So why not using a client side script, like javascript?

I want to share how I did this to you, and also the process of creating a calculator.

Setup a new project
I use FlashDevelop for Flex applications. Create a new project ( Menu > Project > Flex 3 project). Open the main.mxml file in the src-folder. Make shure it is set to ‘always compile’ (the green icon). Let’s add some data:




What did we just created? Check out the code and press ctrl-enter to run the application. We have a container panel, an input field and an output field. Press the button and the text from the input will be shown in the output textfield. Great, isn’t it?

To be real; if you never ever used Flex, this ÍS great. How much time did we spend to create a simple interface like this? We just used 5 tags, and it already is an application.

Basic layout of a flex calculator

Create a html document
We need html, because we need to communicate between the swf and javascript.
[html]



My calculator



[/html]No, nothing special, just another html file. It’s better to use swfObject for embedding flashfiles, but that’s not what this tutorial is about. Save the html document in the same directory as the .swf file (in my case: in the bin folder)

Let’s calculate
We need our flex application to calculate! Let’s add some script (actionscript) to the application. Put this somewhere between the mx:Application tag:


private function eval( str:String ):String
{
return ExternalInterface.call ( “eval”, str );
};
With externalinterface we can communicate between flash and javascript. We have just created an internal function named ‘eval’. This is going to be the function for the calculator. This function uses a string. Externalinterface calls the javascript function “eval” with the parameter from the function and returns that string. This is the magical trick in this tutorial, so make shure you get this point 😉 You have created an actionscript function called eval, that uses the eval function from javascript. I think this is a really global function, so you can use it in other AS3 projects too.

Alright, let’s edit the calculate-button like this:Now build the project and open the html document we have created earlier. Note: from now on just build your project en hit refresh on your browser. You can’t calculate within the FlashPlayer, because javascript calculates for us, remember?

Now we have a very simple calculator.

Let’s make it better. We don’t need two textfields (input / output), but we need one uneditable field. I choose to use a mx:Label, please don’t ask me why. We also need buttons, just like the windows calculator. The button need to add text to our label-field. For that, let’s add a new AS3-function to the mx:Script tag:private function addText( str:String ):void
{
input.text += str;
}
This is straight forward. When we call the function, the input field adds text that is passed by the function. I used a function for this, because we are going to use it more than 1 time. You could use this inline in the buttons, but we need a lot of buttons. Maybe later we would edit this, so then we only have to edit the function, instead of copy/paste this multiple times.
Make a button to test it. Add somewhere a button like this:Test the movie. It works! You can delete the button.

Now, let’s add the other buttons. I used a mx:Panel with an absolute layout, so we can use x and y positions. I changed the layout a bit, and created something this: (this also is the the full code)




















private function eval( str:String ):String
{
if ( ExternalInterface.available )
{
return ExternalInterface.call ( “eval”, str );
}
else
{
return “Unavailable”
}
}
private function addText( str:String ):void
{
input.text += str;
}


What are you waiting for? Run the application 😀

Layout of your flex calculator

Well, that looks different! Take a look at the code. We have created buttons like 0-9, and some math signs. This buttons don’t calculate, they just add text. We have changed the ‘calculate’-button’ to an ‘=’ sign, and we have a clear button.

I think this is a start of using Flex and building a calculator. I’m learning Flex too, so correct me if i’m doing something wrong.

10 responses to “Flex tutorial – Build a calculator”

  1. Bill Gates says:

    I really suggest that you use my own faggotish program; Silverlight.

  2. smarkamyth says:

    This should work without calling the ExternalInterface for Javascript eval:

    input.text = parseInt(input.text).toString();

  3. smarkamyth says:

    Heh . . . sorry!

    parseFloat is going to make a much more interesting and usable calculator.

    input.text = parseFloat(input.text).toString();

  4. Narendar says:

    if i evaluate and press any number, it is taking with result number (which wrong way), instead of clear and start with latest values..as normal calculator behaves.
    can anyone do it for me…
    ………………………
    thanks in advance!

    Narendar.

  5. Dave says:

    I’m just starting to learn flex, I tried this script out and it works fine as a web application but when I tried to build it as an AIR app I get the “UNAVAILIBLE” message. How do I get around that?

    Thanks

  6. Mary Bee says:

    OKAYY I NEED HELP!!!!!!!!!!
    im making a calculator in class on flex, but its not like the calculator u have up there instead i have 6 buttons: Add, Subtract, Multiply, Divide, C (clear) and Equals (=). Then at the top I have two input boxes, my teacher wants me to be able to type in the number press a button (ex. add or sub) then type in another number into the same input box, have it store the first number and the operation. then when i press equal button to have it come up in the other input text box. I AM SOOO LOST. PLEASE SOMEONE HELP. EMAIL ME AT sugar_shoes@hotmail.com

  7. Mark says:

    You need to add this to the script tag

    private function init(e:Event):void
    {
    this.setFocus();
    }

    private function onKeyDown(e:KeyboardEvent):void
    {
    trace(e.keyCode);
    switch (e.keyCode)
    {
    case 49:
    addText(“1”);
    break;
    case 50:
    addText(“2”);
    break;
    }
    }

    ..and this should be added to the mc:Application tag:

    <mx:Application initialize="init(event)" keyDown="onKeyDown(event)" ..

  8. Tommy says:

    This is exactly what i was looking for! I didn’t know ExternalInterface has this function. i was coding my own math logics. what a PITA! this made my app a lot skinnier! Thanks for putting up this tut.

  9. freak says:

    Hello,

    How can i port this to adobe air/

    Thanks.

  10. siri says:

    Hi………….

    i want calculator program in flex………could u give me some logics……

Say something interesting

Please link to code from an external resource, like gist.github.com.