Applying styles to custom components

Style properties define the look of a component, from the size of the fonts used to the color of the background. Your custom ActionScript components inherit all of the styles of the base class, so you can set them in the same way as for that base class.

To change style properties in custom components, use the setStyle() method in the component’s constructor. This applies the same style to all instances of the component, but users of the component can override the settings of the setStyle() method in MXML tags. Any style properties that are not set in the component’s class file are inherited from the component’s superclass.

The following ActionScript class file sets the color and fontWeight styles of the BlueButton control:

package myComponents
{
    // createcomps_as/myComponents/BlueButton.as
    import spark.components.Button;

    public class BlueButton extends Button 
    {
    
        public function BlueButton() {
            super();

            // Set the label text to blue.
            setStyle("color", 0x0000FF);

            // Set the borderColor to blue.
            setStyle("fontWeight", "bold");
        }
    }
}

The following MXML file uses the BlueButton control with the default color and fontWeight styles set in your component’s class file:

<?xml version="1.0"?> 
<!-- createcomps_as/ASMainBlueButton.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx" 
    xmlns:MyComps="myComponents.*">

    <MyComps:BlueButton label="Submit"/>
      
</s:Application>

The executing SWF file for the previous example is shown below:

Setting the styles in a constructor does not prevent users of the component from changing the style. For example, the user could still set their own value for the color style, as the following example shows:

<?xml version="1.0"?> 
<!-- as/MainBlueButtonRed.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx" 
    xmlns:MyComps="myComponents.*">

    <MyComps:BlueButton label="Submit" color="0xFF0000"/>
      
</s:Application>

The executing SWF file for the previous example is shown below:

In addition to setting the color property, you can set the font face, font size, and other style properties. For more information on the available style properties, see the parent control’s class information.

You can also define new style properties for your components. For more information, see Custom style properties.

Applying styles from a defaults.css file

If you package your component in a SWC file, you can define a global style sheet, named defaults.css, in the SWC file. The defaults.css file defines the default style settings for all of the components defined in the SWC file.

For more information, see Applying styles from a defaults.css file.