Friday, September 17, 2010

LabelTextInput in Flex 3

Looking for a Flex 3 component which acts like a TextInput and Label. The following component achieves the purpose. This component will act like a Label by default. But 'on mouse over' it will turn into a TextInput where we can enter text and 'on mover out' it will be again changed to Label.

LabelTextInput.as

package
{
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.MouseEvent;

import mx.controls.TextInput;

public class LabelTextInput extends TextInput
{
public function LabelTextInput()
{
super();
addEventListener(MouseEvent.MOUSE_OVER,onMouseOver);
addEventListener(MouseEvent.MOUSE_OUT,onMouseOut);
addEventListener(Event.CHANGE,onChange);
addEventListener( FocusEvent.FOCUS_IN, onFocusIn );
addEventListener( FocusEvent.FOCUS_OUT, onFocusOut );

this.setStyle("borderStyle","none");
this.setStyle("backgroundAlpha",0);
}

private var _promptText:String = '';
private var _previousText:String;

public function set promptText(value:String):void
{
_promptText = value;
super.text = value;
this.setStyle("fontStyle","italic");
}

public function get promptText():String
{
return _promptText;
}

override public function set text(value:String):void
{
if(value != '')
{
this.setStyle("fontStyle","normal");
super.text = value;
}
else
{
this.setStyle("fontStyle","italic");
super.text = _promptText;
}
}

override public function get text():String
{
if(super.text == _promptText)
return "";
else
return super.text;
}

private function onMouseOver(event:MouseEvent):void
{
this.setStyle("borderStyle","outset");
if(super.text == '')
{
promptText = _promptText;
}
}

private function onMouseOut(event:MouseEvent):void
{
this.setStyle("borderStyle","none");
}

private function onChange(event:Event):void
{
if(super.text == _promptText)
{
this.setStyle("fontStyle","italic");
}
else
{
this.setStyle("fontStyle","normal");
this.setFocus();
}
}

private function onFocusIn(event:FocusEvent):void
{
if(super.text == _promptText)
{
this.setSelection(0,textField.text.length);
this.setFocus();
}
}

private function onFocusOut(event:FocusEvent):void
{
this.setStyle("borderStyle","none");
}
}
}

Feel free to leave your comments.