Sunday, May 25, 2008

Simple Buttons

In theory, simple buttons should be simple to create in Open Source ActionScript. Unfortunately, getting all the details right isn't that easy. It took me a few hours to get this class to work exactly like modern GUIs -- Windows, GNOME, and KDE.

This class allows for three images to be used as a button:
  • Up state: This is the initial image for a button, when the mouse is not over or pressed.
  • Over state: This is the image when the mouse is over the button.
  • Down state: This is the image when the mouse is pressed over the button.
This entry will demonstrate how to create a button with images and map an event when it is clicked.
  1. Right click and save this image () as red_rect.png in the src directory. This will be our "up state".
    On my machine, the full path is:
    /home/kca/workspace/hello_world/src/
  2. Right click and save this image () as pink_rect.png in the src directory. This will be our "over state".
  3. Right click and save this image () as light_pink_rect.png in the src directory. This will be our "down state".
  4. Copy and paste this XML into asset.xml in the src directory
  5. At the command prompt, run this command in the src directory:
    swfmill simple asset.xml asset.swf
  6. This will rebuild the asset library. A new SWF file should now exist in the src directory called asset.swf.
  7. Add a new ActionScript Class in the oas2 subfolder called SimpleButton. Copy and paste this code. Save changes.
  8. Add a new ActionScript Class in the oas2 subfolder called GlobalMouse. Copy and paste this code. Save changes.
    This class contains utility mouse routines used by class SimpleButton.
  9. Double click source file Application.as to edit
  10. Above the class declaration:
    import oas2.SimpleButton ;
  11. At the bottom of function init, add this code:
    var my_button:SimpleButton =
    SimpleButton.create(this, "my_button", 25, 300,
    "asset_red_rect", "asset_pink_rect", "asset_light_pink_rect") ;
    var char_counter:Number = 1 ;
    var instance:Application = this ;

    my_button.onRelease = function() {

    instance._hello_world_text_field.text = hello_world_text.substring(0, char_counter) ;
    ++char_counter ;
    if (char_counter > hello_world_text.length) {

    char_counter = 1 ;

    } // end if (char_counter > hello_world_text.length)

    } ; // end my_button.onRelease = function()
  12. Save the file, and the SWF file is automatically rebuilt by Eclipse. Click to see the new red button in the bottom left. Move the mouse over and the color changes to pink; press the mouse down and it becomes light pink.
  13. Click the button to see the words "Hello, World!" spelled, one character for each click.


No comments: