Friday, September 24, 2010

Using the Button component: Part 5

In this tutorial we will learn how to format the label text on our button.

To change the label's font, size, color, etc. you will need to create a TextFormat object. When you're done setting properties for your TextFormat, you can pass it to the button through setStyle method.

Here is an example button with a formatted label text:


First we create the TextFormat class object.

import flash.text.TextFormat;

var myFormat:TextFormat = new TextFormat();
myFormat.font="Courier New"
myFormat.size=16
myFormat.color=0x0066FF
myFormat.bold=true
myFormat.italic=true

Now we have to set the button's style. If we set it to 'textFormat', the label will be formatted according to our myFormat object. If we set it to 'disabledTextFormat', it is going to change the text appearance when the button is disabled. I created another text format for disabled text and then set the styles.

var myDisabledFormat:TextFormat = new TextFormat();
myDisabledFormat.font="Courier New"
myDisabledFormat.size=16
myDisabledFormat.color=0xFF0000

toggleButton.setStyle("textFormat", myFormat);
toggleButton.setStyle("disabledTextFormat", myDisabledFormat);
toggleButton.setSize(100,40)

Final step: creating the buttons to enable/disable our main button.

enableB.addEventListener(MouseEvent.CLICK, enableF);

function enableF(MouseEvent):void{
toggleButton.enabled=true
toggleButton.label="Enabled"
}

disableB.addEventListener(MouseEvent.CLICK, disableF);

function disableF(MouseEvent):void{
toggleButton.enabled=false
toggleButton.label="Disabled"
}

So the full code would be:

import flash.text.TextFormat;

var myFormat:TextFormat = new TextFormat();
myFormat.font="Courier New"
myFormat.size=16
myFormat.color=0x0066FF
myFormat.bold=true
myFormat.italic=true

var myDisabledFormat:TextFormat = new TextFormat();
myDisabledFormat.font="Courier New"
myDisabledFormat.size=16
myDisabledFormat.color=0xFF0000

toggleButton.setStyle("textFormat", myFormat);
toggleButton.setStyle("disabledTextFormat", myDisabledFormat);
toggleButton.setSize(100,40)

enableB.addEventListener(MouseEvent.CLICK, enableF);

function enableF(MouseEvent):void{
 toggleButton.enabled=true
 toggleButton.label="Enabled"
 }
 
disableB.addEventListener(MouseEvent.CLICK, disableF);

function disableF(MouseEvent):void{
 toggleButton.enabled=false
 toggleButton.label="Disabled"
 }

If we want to change the overall look of the button, just open it from library and edit what you wish. For example, here I made the button turn yellow when I roll over it:



Thank you for reading!

Related:

Using Button component part 1
Using Button component part 2
Using Button component part 3
Using Button component part 4

No comments:

Post a Comment