Implementing the component

When you create a custom component in ActionScript, you have to override the methods of the UIComponent class. You implement the basic component structure, the constructor, and the createChildren(), commitProperties(), measure(), layoutChrome(), and updateDisplayList() methods.

Basic component structure

The following example shows the basic structure of a Flex component:

package myComponents 
{ 
    public class MyComponent extends UIComponent 
    {     
        .... 
    } 
}

You must define your ActionScript custom components within a package. The package reflects the directory location of your component within the directory structure of your application.

The class definition of your component must be prefixed by the public keyword. A file that contains a class definition can have one, and only one, public class definition, although it can have additional internal class definitions. Place any internal class definitions at the bottom of your source file below the closing curly brace of the package definition.

Implementing the constructor

Your ActionScript class should define a public constructor method for a class that is a subclass of the UIComponent class, or a subclass of any child of the UIComponent class. The constructor has the following characteristics:

  • No return type

  • Should be declared public

  • No arguments

  • Calls the super() method to invoke the superclass’ constructor

Each class can contain only one constructor method; ActionScript does not support overloaded constructor methods. For more information, see Defining the constructor.

Use the constructor to set the initial values of class properties. For example, you can set default values for properties and styles, or initialize data structures, such as Arrays.

Do not create child display objects in the constructor; you should use it only for setting initial properties of the component. If your component creates child components, create them in the createChildren() method.

Implementing the createChildren() method for MX components

A component that creates other components or visual objects within it is called a composite component. For example, the Flex ComboBox control contains a TextInput control to define the text area of the ComboBox, and a Button control to define the ComboBox arrow. Components implement the createChildren() method to create child objects (such as other components) in the component.

You do not call the createChildren() method directly; Flex calls it when the call to the addChild() method occurs to add the component to its parent. Notice that the createChildren() method has no invalidation method, which means that you do not have to call it a second time after the component is added to its parent.

For example, you might define a new component that consists of a Button control and a TextArea control, where the Button control enables and disables user input to the TextArea control. The following example creates the TextArea and Button controls:

// Declare two variables for the component children. 
private var text_mc:TextArea; 
private var mode_mc:Button; 
 
override protected function createChildren():void { 
 
    // Call the createChildren() method of the superclass. 
    super.createChildren(); 
         
    // Test for the existence of the children before creating them. 
    // This is optional, but do this so a subclass can create a different 
    // child. 
    if (!text_mc)     { 
        text_mc = new TextArea(); 
        text_mc.explicitWidth = 80; 
        text_mc.editable = false; 
        text_mc.addEventListener("change", handleChangeEvent); 
        // Add the child component to the custom component. 
        addChild(text_mc); 
    } 
 
    // Test for the existence of the children before creating them. 
    if (!mode_mc)     {     
        mode_mc = new Button(); 
        mode_mc.label = "Toggle Editing"; 
        mode_mc.addEventListener("click", handleClickEvent); 
        // Add the child component to the custom component. 
        addChild(mode_mc); 
    } 
}

Notice in this example that the createChildren() method calls the addChild() method to add the child component. You must call the addChild() method for each child object.

After you create a child component, you can use properties of the child component to define its characteristics. In this example, you create the Button and TextArea controls, initialize them, and register event listeners for them. You could also apply skins to the child components. For a complete example, see Example: Creating a composite MX component.

Implementing the commitProperties() method for MX components

You use the commitProperties() method to coordinate modifications to component properties. Most often, you use it with properties that affect how a component appears on the screen.

Flex schedules a call to the commitProperties() method when a call to the invalidateProperties() method occurs. The commitProperties() method executes during the next render event after a call to the invalidateProperties() method. When you use the addChild() method to add a component to a container, Flex automatically calls the invalidateProperties() method.

Calls to the commitProperties() method occur before calls to the measure() method. This lets you set property values that the measure() method might use.

The typical pattern for defining component properties is to define the properties by using getter and setter methods, as the following example shows:

// Define a private variable for the alignText property. 
private var _alignText:String = "right"; 
 
// Define a flag to indicate when the _alignText property changes. 
private var bAlignTextChanged:Boolean = false; 
 
// Define getter and setter methods for the property.         
public function get alignText():String { 
        return _alignText; 
} 
 
public function set alignText(t:String):void { 
    _alignText = t; 
    bAlignTextChanged = true; 
 
    // Trigger the commitProperties(), measure(), and updateDisplayList()  
    // methods as necessary.  
    // In this case, you do not need to remeasure the component.  
    invalidateProperties(); 
    invalidateDisplayList(); 
} 
 
// Implement the commitProperties() method.  
override protected function commitProperties():void { 
    super.commitProperties(); 
     
    // Check whether the flag indicates a change to the alignText property.  
    if (bAlignTextChanged) { 
        // Reset flag. 
        bAlignTextChanged = false; 
 
        // Handle alignment change 
    } 
}

As you can see in this example, the setter method modifies the property, calls the invalidateProperties() and invalidateDisplayList() methods, and then returns. The setter itself does not perform any calculations based on the new property value. This design lets the setter method return quickly, and leaves any processing of the new value to the commitProperties() method.

Changing the alignment of text in a control does not necessarily change the control’s size. However, if it does, include a call to the invalidateSize() method to trigger the measure() method.

The main advantages of using the commitProperties() method are the following:

  • To coordinate the modifications of multiple properties so that the modifications occur synchronously.

    For example, you might define multiple properties that control the text displayed by the component, such as the alignment of the text within the component. A change to either the text or the alignment property requires Flex to update the appearance of the component. However, if you modify both the text and the alignment, you want Flex to perform any calculations for sizing or positioning the component once, when the screen updates.

    Therefore, you use the commitProperties() method to calculate any values based on the relationship of multiple component properties. By coordinating the property changes in the commitProperties() method, you can reduce unnecessary processing overhead.

  • To coordinate multiple modifications to the same property.

    You do not necessarily want to perform a complex calculation every time a user updates a component property. For example, users modify the icon property of the Button control to change the image displayed in the button. Calculating the label position based on the presence or size of an icon can be a computationally expensive operation that you want to perform only when necessary.

    To avoid this behavior, you use the commitProperties() method to perform the calculations. Flex calls the commitProperties() method when it updates the display. That means you perform the calculations once when Flex updates the screen, regardless of the number of times the property changed between screen updates.

The following example shows how you can handle two related properties in the commitProperties() method:

// Define a private variable for the text property. 
private var _text:String = "ModalText"; 
private var bTextChanged:Boolean = false; 
         
// Define the getter method.  
public function get text():String { 
        return _text; 
} 
 
//Define the setter method to call invalidateProperties()  
// when the property changes.  
public function set text(t:String):void { 
    _text = t; 
    bTextChanged = true; 
    invalidateProperties(); 
    // Changing the text causes the control to recalculate its default size. 
    invalidateSize(); 
    invalidateDisplayList(); 
} 
 
// Define a private variable for the alignText property. 
private var _alignText:String = "right"; 
private var bAlignTextChanged:Boolean = false; 
         
public function get alignText():String { 
        return _alignText; 
} 
     
public function set alignText(t:String):void { 
    _alignText = t; 
    bAlignTextChanged = true; 
    invalidateProperties(); 
    invalidateDisplayList(); 
} 
     
// Implement the commitProperties() method.  
override protected function commitProperties():void { 
    super.commitProperties(); 
 
    // Check whether the flags indicate a change to both properties.  
    if (bTextChanged && bAlignTextChanged) { 
        // Reset flags. 
        bTextChanged = false; 
        bAlignTextChanged = false; 
 
        // Handle case where both properties changed. 
    } 
     
    // Check whether the flag indicates a change to the text property.  
    if (bTextChanged) { 
        // Reset flag. 
        bTextChanged = false; 
 
        // Handle text change. 
    } 
 
    // Check whether the flag indicates a change to the alignText property.  
    if (bAlignTextChanged) { 
        // Reset flag. 
        bAlignTextChanged = false; 
 
        // Handle alignment change. 
    } 
}

Implementing the measure() method for MX components

The measure() method sets the default component size, in pixels, and optionally sets the component’s default minimum size.

Flex schedules a call to the measure() method when a call to the invalidateSize() method occurs. The measure() method executes during the next render event after a call to the invalidateSize() method. When you use the addChild() method to add a component to a container, Flex automatically calls the invalidateSize() method.

When you set a specific height and width of a component, Flex does not call the measure() method, even if you explicitly call the invalidateSize() method. That is, Flex calls the measure() method only if the explicitWidth property or the explicitHeight property of the component is NaN.

In the following example, because you explicitly set the size of the Button control, Flex does not call the Button.measure() method:

<mx:Button height="10" width="10"/>

In a subclass of an existing component, you might implement the measure() method only if you are performing an action that requires modification to the default sizing rules defined in the superclass. Therefore, to set a new default size, or perform calculations at run time to determine component sizing rules, implement the measure() method.

You set the following properties in the measure() method to specify the default size:

Properties

Description

measuredHeightmeasuredWidth

Specifies the default height and width of the component, in pixels.

These properties are set to 0 until the measure() method executes. Although you can leave them set to 0, it makes the component invisible by default.

measuredMinHeightmeasuredMinWidth 

Specifies the default minimum height and minimum width of the component, in pixels. Flex cannot set the size of a component smaller than its specified minimum size.

The measure() method only sets the default size of the component. In the updateDisplayList() method, the parent container of the component passes to it its actual size, which may be different than the default size.

Component users can also override the default size settings in an application by using the component in the following ways:

  • Setting the explicitHeight and exlicitWidth properties

  • Setting the width and height properties

  • Setting the percentHeight and percentWidth properties

For example, you can define a Button control with a default size of 100 pixels wide and 50 pixels tall, and a default minimum size of 50 pixels by 25 pixels, as the following example shows:

package myComponents
{
    // asAdvanced/myComponents/BlueButton.as
    import mx.controls.Button;

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

        override protected function measure():void {
            super.measure();
    
            measuredWidth=100;
            measuredMinWidth=50;
            measuredHeight=50;
            measuredMinHeight=25;
        }
    }
}

The following application uses this button in an application:

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

    <mx:VBox>
        <MyComp:BlueButton/>
        <mx:Button/>
    </mx:VBox>
</s:Application>

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

In the absence of any other sizing constraints on the button, the VBox container uses the default size and default minimum size of the button to calculate its size at run time. For information on the rules for sizing a component, see Introduction to containers.

You can override the default size settings in an application, as the following example shows:

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

    <mx:VBox>
        <MyComp:BlueButton width="50%"/>
        <mx:Button/>
    </mx:VBox>
</s:Application>

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

In this example, you specify that the width of the button is 50% of the width of the VBox container. When 50% of the width of the container is smaller than the minimum width of the button, the button uses its minimum width.

Calculating default sizes

The example in Implementing the measure() method for MX components uses static values for the default size and default minimum size of a component. Some Flex components use static sizes. For example, the TextArea control has a default size of 100 pixels wide by 44 pixels high, regardless of the text it contains. If the text is larger than the TextArea control, the control displays scroll bars.

Often, you set the default size based on characteristics of the component or information passed to the component. For example, the Button control’s measure() method examines its label text, margin settings, and font characteristics to determine the control’s default size.

In the following example, you override the measure() method of the TextArea control so that it examines the text passed to the control, and calculates the default size of the TextArea control to display the entire text string in a single line:

package myComponents
{ 
    // asAdvanced/myComponents/MyTextArea.as
    import mx.controls.TextArea;
    import flash.text.TextLineMetrics;

    public class MyTextArea extends TextArea
    {

        public function MyTextArea() {
            super();
        }
        
        // The default size is the size of the text plus a 10 pixel margin.
        override protected function measure():void {
            super.measure();

            // Calculate the default size of the control based on the 
            // contents of the TextArea.text property.
            var lineMetrics:TextLineMetrics = measureText(text);
            // Add a 10 pixel border area around the text.
            measuredWidth = measuredMinWidth = lineMetrics.width + 10;
            measuredHeight = measuredMinHeight = lineMetrics.height + 10;
        }
    }
}

For text strings that are longer than the display area of your application, you can add logic to increase the height of the TextArea control to display the text on multiple lines. The following application uses this component:

<?xml version="1.0"?> 
<!-- asAdvanced/MainMyTextArea.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:mx="library://ns.adobe.com/flex/mx" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:MyComp="myComponents.*" 
    width="1000">
    <s:layout>
        <s:VerticalLayout/>
    </s:layout>

    <MyComp:MyTextArea id="myTA" text="This is a long text strring that would normally cause a TextArea control to display scroll bars. But, the custom MyTextArea control calcualtes its default size based on the text size."/>
    
    <mx:TextArea id="flexTA" text="This is a long text strring that would normally cause a TextArea control to display scroll bars. But, the custom MyTextArea control calcualtes its default size based on the text size."/>

</s:Application>

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

Implementing the layoutChrome() method for MX components

The Container class, and some subclasses of the Container class, use the layoutChrome() method to define the border area around the container.

Flex schedules a call to the layoutChrome() method when a call to the invalidateDisplayList() method occurs. The layoutChrome() method executes during the next render event after a call to the invalidateDisplayList() method. When you use the addChild() method to add a component to a container, Flex automatically calls the invalidateDisplayList() method.

Typically, you use the RectangularBorder class to define the border area of a container. For example, you can create the RectangularBorder object, and add it as a child of the component in your override of the createChildren() method.

When you create a subclass of the Container class, you can use the createChildren() method to create the content children of the container; the content children are the child components that appear within the container. You then use updateDisplayList() to position the content children.

You typically use the layoutChrome() method to define and position the border area of the container, and any additional elements that you want to appear in the border area. For example, the Panel container uses the layoutChrome() method to define the title area of the panel container, including the title text and close button.

The primary reason for dividing the handling of the content area of a container from its border area is to handle the situation when the Container.autoLayout property is set to false. When the autoLayout property is set to true, measurement and layout of the container and of its children are done whenever the position or size of a container child changes. The default value is true.

When the autoLayout property is set to false, measurement and layout are done only once, when children are added to or removed from the container. However, Flex executes the layoutChrome() method in both cases. Therefore, the container can still update its border area even when the autoLayout property is set to false.

Implementing the updateDisplayList() method for MX components

The updateDisplayList() method sizes and positions the children of your component based on all previous property and style settings, and draws any skins or graphic elements that the component uses. The parent container for the component determines the size of the component itself.

A component does not appear on the screen until its updateDisplayList() method gets called. Flex schedules a call to the updateDisplayList() method when a call to the invalidateDisplayList() method occurs. The updateDisplayList() method executes during the next render event after a call to the invalidateDisplayList() method. When you use the addChild() method to add a component to a container, Flex automatically calls the invalidateDisplayList() method.

The main uses of the updateDisplayList() method are the following:

  • To set the size and position of the elements of the component for display.

    Many components are made up of one or more child components, or have properties that control the display of information in the component. For example, the Button control lets you specify an optional icon, and use the labelPlacement property to specify where the button text appears relative to the icon.

    The Button.updateDisplayList() method uses the settings of the icon and labelPlacement properties to control the display of the button.

    For containers that have child controls, the updateDisplayList() method controls how those child components are positioned. For example, the updateDisplayList() method on the HBox container positions its children from left to right in a single row; the updateDisplayList() method for a VBox container positions its children from top to bottom in a single column.

    To size components in the updateDisplayList() method, you use the setActualSize() method, not the sizing properties, such as width and height. To position a component, use the move() method, not the x and y properties.

  • To draw any visual elements necessary for the component.

    Components support many types of visual elements such as skins, styles, and borders. Within the updateDisplayList() method, you can add these visual elements, use the Flash drawing APIs, and perform additional control over the visual display of your component.

The updateDisplayList() method has the following signature:

protected function updateDisplayList(unscaledWidth:Number, 
    unscaledHeight:Number):void

The properties have the following values:

unscaledWidth 
Specifies the width of the component, in pixels, in the component’s coordinates, regardless of the value of the scaleX property of the component. This is the width of the component as determined by its parent container.

unscaledHeight 
Specifies the height of the component, in pixels, in the component’s coordinates, regardless of the value of the scaleY property of the component. This is the height of the component as determined by its parent container.

Scaling occurs in Flash Player or AIR, after updateDisplayList() executes. For example, a component with an unscaledHeight value of 100, and with a scaleY property of 2.0, appears 200 pixels high in Flash Player or AIR.

Overriding the layout mechanism of the VBox container

The VBox container lays out its children from the top of the container to the bottom, in the order in which the children are added to the container. The following example overrides the updateDisplayList() method, which causes the VBox container to layout its children from the bottom of the container to the top:

package myComponents
{ 
    // asAdvanced/myComponents/BottomUpVBox.as
    import mx.containers.VBox;
    import mx.core.EdgeMetrics;
    import mx.core.UIComponent;

    public class BottomUpVBox extends VBox
    {
    
        public function BottomUpVBox() {
            super();
        }
        
        override protected function updateDisplayList(unscaledWidth:Number,
            unscaledHeight:Number):void {

            super.updateDisplayList(unscaledWidth, unscaledHeight);
    
            // Get information about the container border area. 
            // The usable area of the container for its children is the 
            // container size, minus any border areas.
            var vm:EdgeMetrics = viewMetricsAndPadding;

            // Get the setting for the vertical gap between children.
            var gap:Number = getStyle("verticalGap");
    
            // Determine the y coordinate of the bottom of the usable area 
            // of the VBox.
            var yOfComp:Number = unscaledHeight-vm.bottom;
            
            // Temp variable for a container child.
            var obj:UIComponent;
                
            for (var i:int = 0; i < numChildren; i++)
            {
                // Get the first container child.
                obj = UIComponent(getChildAt(i));
            
                // Determine the y coordinate of the child.
                yOfComp = yOfComp - obj.height;
                
                // Set the x and y coordinate of the child.
                // Note that you do not change the x coordinate.
                obj.move(obj.x, yOfComp);
                
                // Save the y coordinate of the child,  
                // plus the vertical gap between children. 
                // This is used to calculate the coordinate 
                // of the next child. 
                yOfComp = yOfComp - gap;
            }
        }
    }
}

In this example, you use the UIComponent.move() method to set the position of each child in the container. You can also use the UIComponent.x and UIComponent.y properties to set these coordinates. The difference is that the move() method changes the location of the component and then dispatches a move event when you call the method immediately; setting the x and y properties changes the location of the component and dispatches the event on the next screen update.

The following application uses this component:

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

  <MyComp:BottomUpVBox>  
    <mx:Label text="Label 1"/>
    <mx:Button label="Button 1"/>

    <mx:Label text="Label 2"/>
    <mx:Button label="Button 2"/>
    
    <mx:Label text="Label 3"/>
    <mx:Button label="Button 3"/>

    <mx:Label text="Label 4"/>
    <mx:Button label="Button 4"/>

  </MyComp:BottomUpVBox>  
</s:Application>

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

Drawing graphics in your component

Every Flex component is a subclass of the Flash Sprite class, and therefore inherits the Sprite.graphics property. The Sprite.graphics property specifies a Graphics object that you can use to add vector drawings to your component.

For example, in the updateDisplayList() method, you can use methods of the Graphics class to draw borders, rules, and other graphical elements:

override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { 
 
    super.updateDisplayList(unscaledWidth, unscaledHeight); 
     
    // Draw a simple border around the child components. 
    graphics.lineStyle(1, 0x000000, 1.0); 
    graphics.drawRect(0, 0, unscaledWidth, unscaledHeight);             
}