Styling a Button control

I was going through my blog the other night and it occurred to me, I do a pretty half-assed job of explaining things on my blog. For instance, take something basic like styling a Button. Usually I’ll just show how to use a single style, property, method, or technique and call it a day. Very rarely would I demonstrate a few different ways of accomplishing a task. For the most part this isn’t a huge deal, but in some cases it seems like I’m somehow cutting corners.

So, with that in mind, the following example shows a few different ways you can apply a style to a Button control. Note, these aren’t really in any sort of particular order, just whichever way I thought of them and typed them into Flex Builder.

First up is what I consider the easiest form of styling. Just specify the style name and value directly in the MXML tag. Simple and right to the point. Probably not the most flexible approach as if you did this throughout an entire application and then wanted to change something, its a lot of search and replace and a bit of a headache.

<mx:Button label="Button 1" borderColor="red" />

While I really appreciate the simplicity of it, I have to admit that it is a bit difficult to see if borderColor is a property, or style, or event, or…

Next, similar to the first method, you can specify the borderColor property in a nested <mx:borderColor> block. Personally I don’t see a big advantage to this method over the first method. It is a bit more typing and doesn’t seem to add much. Although I must admit that I will use this in my code for more complex values, such as defining data grid columns, or data providers.

<mx:Button label="Button 2">
    <mx:borderColor>red</mx:borderColor>
</mx:Button>

Again, for something simple like the borderColor style, probably a bit of overkill.

Next, styling using an <mx:Style> block. There are a few different ways you can do this too. You could specify a style for the Button class generically, and that would apply to each Button instance on the display list. Or, you could specify a custom style name (as shown below) and apply that style individually to certain Button instances within your application instead of every Button instance automatically.

<mx:Style>
    .MyButton {
        borderColor: red;
    }
</mx:Style>

<mx:Button label="Button 3" styleName="MyButton" />

As you can see we created a new style in our <mx:Style /> block, and gave it a name of “MyButton”. To apply that specific style to a Button (or any other container or control, for that matter), simply set the styleName property (inherited from the UIComponent class) to the name of the style (minus the leading period, so in this example set the style name to “MyButton” and NOT “.MyButton”).

If you wanted to style ALL Button controls, you could use the following code instead:

<mx:Style>
    Button {
        borderColor: red;
    }
</mx:Style>

<mx:Button label="Button 3" />

Note that we no longer need to specify the styleName property since the Button style will automatically be used for each Button control on the display list.

Also note that you can move the style declarations into an external file and load them in at compile-time using the following code:

<mx:Style source="styles.css" />

<mx:Button label="Button 3" />

And then create a file named “styles.css” which is in the same directory as your MXML file. So, for the following example I created a styles.css file and added the following content:

/* CSS file */
Button {
    borderColor: red;
}

Moving the CSS declarations out of the MXML and into their own separate files has the added benefit of being a lot more reusable when working with larger applications. Plus, it can be a lot easier to manage styles if they’re all kept neatly in one single place instead of distributed throughout multiple MXML files.

The fourth way to set styles on a container or control is to call the setStyle() method (also inherited from the UIComponent class) from ActionScript. The following example shows how you can create and call an ActionScript method which sets the borderColor style using the setStyle() method:

<mx:Script>
    <![CDATA[
        private function button4_init():void {
            button4.setStyle("borderColor", "red");
        }
    ]]>
</mx:Script>

<mx:Button id="button4"
        label="Button 4"
        creationComplete="button4_init();" />

Note that you wouldn’t typically want to set styles in this exact way (creating a creationComplete event handler which sets the style in question), but I just wanted to show how the setStyle() method was used and keep the code as copy-paste as possible.

Yes, there are still probably a few more ways to style components (notably loading in CSS at runtime and using the StyleManager), but I’ll either save that for another entry, or update this entry at a later date.

Anyways, hopefully this helps shed some light on a few of the different ways that you can change styles from within Flex.

Feel free to leave some comments if there is something you think I missed or want me to add to the post.

As always, play safe, and Happy Flexing!

11 thoughts on “Styling a Button control

  1. Thanks:)

    in this code:

    .MyButton {
        borderColor: red;
    }
    

    How do i change declared Object Css on runtime or with script?

  2. Reza.H,

    Try something similar to the following:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
            layout="vertical"
            verticalAlign="middle"
            backgroundColor="white">
    
        <mx:Style>
            .MyButton {
                borderColor: red;
            }
        </mx:Style>
    
        <mx:Script>
            <![CDATA[
                private function changeBorderColor(value:Object):void {
                    var cssDecl:CSSStyleDeclaration = StyleManager.getStyleDeclaration(".MyButton");
                    if (cssDecl != null) {
                        cssDecl.setStyle("borderColor", value);
                    }
                }
            ]]>
        </mx:Script>
    
        <mx:Button id="button3"
                label="Button 3"
                styleName="MyButton"
                click="changeBorderColor('haloOrange');" />
    
    </mx:Application>
    

    You should be able to pass strings such as “red” or “haloBlue” to the changeBorderColor() method, as well as color values such as 0xFF0000.

    Hope that helps,
    Peter

  3. Hi Peter,

    I have 3 buttons and when each one is clicked i would like them each to have a selected state or On effect so, the user will know what section they are in. Currently i am using haloBlue on each button and ideally i would like the haloBlue mouseOver state to stay when each button is selected.

    Is that achievable and if so could you possibly show an example. Thanks! :-)

  4. Hmm… not quite what i had in mind. Nice to know though!

    You know when you click say, a haloGreen button and it changes to a bright green Lozenge type effect?

    I would like that to stay that way until you click the next button. Kinda like switching the button on/off and when you click the next button it switches on and the previous one goes off.

    hope that makes sense? ~ d

  5. I guess in this scenario: is more appropriate for my needs but, i presume i would also need some actionscript to tell it to switch to false when the next button is clicked. Then a style can be applied to change the background of the toggle state from default grey to that bright lozenge effect.

    sorry, i’m relatively new to this Flex stuff :-|

  6. toggle=”true” is what’s missing from the message above.

    I typed the actual mxml tag but it didn’t print out for some reason.

  7. Declan,

    Perhaps not exactly what you want, but have you considered using the ToggleButtonBar control?

    I have an example of it at “Creating a vertical ToggleButtonBar in Flex”.

    You can definitely do what you want with a regular Button control also. Either set the toggle property to true (and possibly the selected property as well). But you’d have to track which button is currently selected and set the other button’s selected property to false. Plus, you may need to override the selectedUpSkin style (and maybe the selectedOverSkin and selectedDownSkin styles as well).

    Hope that helps,
    Peter

  8. Thanks Peter. The ToggleButtonBar is a handy option alright. I’ll persevere with the button control though, as it is still the preferred option for my current project and i will definitely want it again for future projects.

    ~ d :-)

  9. Thanks Peter,
    I seem that this Artical is very benificiary for the begineers as well as others.
    this artical contains a quick summary to use styles in flex. Thanks A lot.
    :)

Comments are closed.