开发者

Creating multiple buttons with dynamic text in AS3

开发者 https://www.devze.com 2023-03-15 01:44 出处:网络
I\'d like to create a Hangman game, only instead of having the player enter a letter, I\'d like to have 26 clickable buttons on the screen. Now, I could make 26 symbols, but that seems ridiculous when

I'd like to create a Hangman game, only instead of having the player enter a letter, I'd like to have 26 clickable buttons on the screen. Now, I could make 26 symbols, but that seems ridiculous when I could create a letter_button.as class and just create 26 instances of letter_button, where I can just do something like letter_button.letter_id to get the value.

That part's easy. The hard part is, uh. Well. 1- How do I create a button that will accept dynamic text?

2- How do I add these buttons to the stage? Will parent.addChild(new lett开发者_StackOverflower_button(letter)) work? Or do I need something else?

Here's how far I've gotten in my solution, tell me if I'm barking up the wrong tree. To begin, I created a button called "Letter_Button". It has a text field on it called "letter_text". It's a MovieClip and it links to Letter_Button.as

Here's the scrappy, half-baked test code:

package  {
import flash.display.MovieClip;

public class hangman_manager extends MovieClip{

    public function hangman_manager() 
   {
        addChild(new Letter_Button("a"));
    }

}

}

And Letter_Button.as:

package  {
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.events.Event;

public class Letter_Button extends SimpleButton {

    public function Letter_Button(letter:String) {
        x = 250 ;
        y = 250 ;
        trace ("Letter is"+ letter);
        addEventListener(Event.ADDED_TO_STAGE,onAddedToStage);

    }


    public function onAddedToStage(event:Event):void
    {
        this.letter_text.text="A"; 
    }

}

}

The problem is this- I keep getting a null object error, I GUESS because the letter_button doesn't exist yet. I had hoped onAddedToStage would fix that, but it doesn't. How am I going wrong here? And have I invented a ridiculous way to do this? Is there a better way?


There already a LabelButton class in as3. Look at the reference here


One way that I've done something like before is to create a movieclip with a bg layer for the button graphic, and a second layer with a dynamic textfield that has the instance name "buttonText".

I then connected the movieclip in the library to a new class called "MyButton". The constructor for MyButton requires a string. The constructor calls a method called setText(txt:String) which does:

this['buttonText'].text = txt;

You could also add MouseEvent listeners to each button to call a returnButtonValue method which would return a variable that holds the txt of that button.

To add them,to the stage just do:

button1 = new MyButton("desired text value");
addChild(btn1);
0

精彩评论

暂无评论...
验证码 换一张
取 消