Using the ColorPicker control’s colorField and labelField properties

In a previous post, “Formatting colors as strings with ActionScript“, A reader asked about the ColorPicker component. So here’s a quick little example of creating a ColorPicker control, as well as setting the labelField and colorField properties to display color names in the ColorPicker control.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundColor="white">

    <mx:Script>
        <![CDATA[
            private function intToHex(color:int = 0):String {
                var mask:String = "000000";
                var str:String = mask + color.toString(16).toUpperCase();
                return "#" + str.substr(str.length - 6);
            }
        ]]>
    </mx:Script>

    <mx:Array id="colorPicker_dataProvider">
        <mx:Object name="black" value="0x000000" />
        <mx:Object name="blue" value="0x0000FF" />
        <mx:Object name="green" value="0x008000" />
        <mx:Object name="gray" value="0x808080" />
        <mx:Object name="silver" value="0xC0C0C0" />
        <mx:Object name="lime" value="0x00FF00" />
        <mx:Object name="olive" value="0x808000" />
        <mx:Object name="white" value="0xFFFFFF" />
        <mx:Object name="yellow" value="0xFFFF00" />
        <mx:Object name="maroon" value="0x800000" />
        <mx:Object name="navy" value="0x000080" />
        <mx:Object name="red" value="0xFF0000" />
        <mx:Object name="purple" value="0x800080" />
        <mx:Object name="teal" value="0x008080" />
        <mx:Object name="fuchsia" value="0xFF00FF" />
        <mx:Object name="aqua" value="0x00FFFF" />
        <mx:Object name="magenta" value="0xFF00FF" />
        <mx:Object name="cyan" value="0x00FFFF" />

        <mx:Object name="halogreen" value="0x80FF4D" />
        <mx:Object name="haloblue" value="0x009DFF" />
        <mx:Object name="haloorange" value="0xFFB600" />
        <mx:Object name="halosilver" value="0xAECAD9" />
    </mx:Array>

    <mx:HBox width="{box.width}">
        <mx:ColorPicker id="colorPicker" dataProvider="{colorPicker_dataProvider}" colorField="value" labelField="name" editable="false" change="box.setStyle('backgroundColor', event.color);" />
        <mx:Label text="{intToHex(colorPicker.selectedColor)} {colorPicker.selectedColor}" />
    </mx:HBox>

    <mx:Box id="box" width="200" height="100" />

</mx:Application>

If you’re curious as to where I got the color names from, you can check out the colorNames object in the mx.styles.StyleManagerImpl class. The class isn’t listed in the documentation, but you can find it in the SDK source code at “frameworks\projects\framework\src\mx\styles\StyleManagerImpl.as”.

Happy Flexing!