Zeeshan Rang
Zeeshan Rang

Reputation: 19915

How to have selectedColor in a colorPicker to be random

I am trying to have a random color to be picked as default for my ColorPicker. I am running my script on the creation complete of my Panel.

The script code is given below:

public var someColor:String = new String();

    private function init():void{
        var myColor:Number = Math.round( Math.random()*0xFFFFFF );
        someColor = "0x"+myColor.toString(16);      
    }

and the code for the ColorPicker is:

<mx:ColorPicker id="calendar_color" width="20" height="20" selectedColor="{someColor}"/>

Even though, when I see the color in the var someColor, it shows a random color every time, but the colorPicker is not displaying the color.

Please let me know, what am I doing wrong here. And how it can be fixed.

Upvotes: 0

Views: 661

Answers (3)

moropus
moropus

Reputation: 3782

1) Why do you have someColor as String? Therefore you've got two unnececcary type conversions: from Number to String (myColor.toString(16)) and from String to uint (selectedColor="{someColor}"). Why not just write this:

[Bindable] public var someColor:uint = 0;

private function init():void{
    someColor = Math.random()*0xFFFFFF; 
}

2) And one more thing I also don't like - in current answer you've got actually uneccecary binding, the one that will only shoot once, and you should not forget to call init() somewhere in youre code. I'd better change it on function call:

private function getRandomColor():uint{
    return Math.random()*0xFFFFFF;
}

<mx:ColorPicker id="calendar_color" width="20" height="20"
    selectedColor="{getRandomColor()}"/>

Here getRandomColor() will be automatically called on ColorPicker initialization. One unavoidable type conversion (from Number to uint), no bindings, no useless property, shorter code.

That's not premature optimization, that's removing premature pessimization.

Upvotes: 2

nhutto
nhutto

Reputation: 163

I can't tell from this post but what class is

    public var someColor:String = new String();

in. you will just want to verify that it can be reached through the reference you made.

Upvotes: 0

Jacob Eggers
Jacob Eggers

Reputation: 9332

You need to add the [Bindable] metadata:

[Bindable]
public var someColor:String = new String();

Upvotes: 0

Related Questions