Search Flex Components Free

Custom Search
Showing posts with label Flex Control Samples. Show all posts
Showing posts with label Flex Control Samples. Show all posts

June 10, 2009

Flex Loading assets

Data compared to content

The Flash Player security model makes a distinction between loading content and accessing or loading data. Content is defined as media: visual media that Flash Player can display, such as audio, video, or a SWF file that includes displayed media. Data is defined as something that you can manipulate only with ActionScript code.

You can load data in one of two ways: by extracting data from loaded media content, or by directly loading data from an external file (such as an XML file) or socket connection. You can extract data from loaded media by using the BitmapData.draw() method, the Sound.id3 property, or the SoundMixer.computeSpectrum() method. You can load data by using classes such as the SWFLoader, URLStream, URLLoader, Socket, and XMLSocket classes.

The Flash Player security model defines different rules for loading content and accessing data. Loading content has fewer restrictions than accessing data. In general, content such as SWF files, bitmaps, MP3 files, and videos can be loaded from anywhere, but if the content is from a domain other than that of the loading SWF file, it will be partitioned in a separate security sandbox.

Loading remote assets

Loading remote or network assets relies on three factors:

  • Type of asset. If the target asset is a content asset, such as an image file, you do not need any specific permissions from the target domain to load its assets into your Flex application. If the target asset is a data asset, such as an XML file, you must have the target domain's permission to access this asset. For more information on the types of assets, see Data compared to content.
  • Target domain. If you are loading data assets from a different domain, the target domain must provide a crossdomain.xml policy file. This file contains a list of URLs and URL patterns that it allows access from. The calling domain must match one of the URLs or URL patterns in that list. For more information about the crossdomain.xml file, see Using cross-domain policy files. If the target asset is a SWF file, you can also provide permissions by calling the loadPolicyFile() method and loading an alternative policy file inside that target SWF file. For more information, see Using cross-domain policy files.
  • Loading SWF file's sandbox. To load an asset from a network address, you must ensure that your SWF file is in either the remote or local-with-networking sandbox. To ensure that a SWF file can load assets over the network, you must set the use-network compiler option totrue when you compile the Flex application. This is the default. If the application was loaded from the local file system with use-networkset to false, the application is put in the local-with-filesystem sandbox and it cannot load remote SWF files.

Loading assets from a remote location that you do not control can potentially expose your users to risks. For example, the remote website B contains a SWF file that is loaded by your website A. This SWF file normally displays an advertisement. However, if website B is compromised and its SWF file is replaced with one that asks for a username and password, some users might disclose their login information. To prevent data submission, the loader has a property called allowNetworking with a default value of never.

Using cross-domain policy files

To make data available to SWF files in different domains, use a cross-domain policy file. A cross-domain policy file is an XML file that provides a way for the server to indicate that its data and documents are available to SWF files served from other domains. Any SWF file that is served from a domain that the server's policy file specifies is permitted to access data or assets from that server.

March 24, 2008

Setting the selected index of a Flex LinkBar control





<?xml version="1.0" encoding="utf-8"?>


<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white">



<mx:Array id="arr">

<mx:Object label="One" />

<mx:Object label="Two" />

<mx:Object label="Three" />

<mx:Object label="Four" />

</mx:Array>



<mx:ApplicationControlBar dock="true">

<mx:Form styleName="plain">

<mx:FormItem label="selectedIndex:">

<mx:HSlider id="slider"

minimum="0"

maximum="{linkBar.dataProvider.length - 1}"

liveDragging="true"

snapInterval="1"

tickInterval="1"

dataTipPrecision="0" />

</mx:FormItem>

</mx:Form>

</mx:ApplicationControlBar>



<mx:LinkBar id="linkBar"

dataProvider="{arr}"

selectedIndex="{slider.value}" />



</mx:Application>






Setting the background color and background alpha on a Flex LinkBar control





<?xml version="1.0" encoding="utf-8"?>


<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white">



<mx:Array id="arr">

<mx:Object label="One" />

<mx:Object label="Two" />

<mx:Object label="Three" />

<mx:Object label="Four" />

</mx:Array>



<mx:ApplicationControlBar dock="true">

<mx:Form styleName="plain">

<mx:FormItem label="backgroundAlpha:">

<mx:HSlider id="slider"

minimum="0.0"

maximum="1.0"

value="1.0"

liveDragging="true" />

</mx:FormItem>

</mx:Form>

</mx:ApplicationControlBar>



<mx:LinkBar id="linkBar"

dataProvider="{arr}"

backgroundAlpha="{slider.value}"

backgroundColor="haloBlue" />



</mx:Application>




Scrolling a Flex List control horizontally





<?xml version="1.0" encoding="utf-8"?>


<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white">



<mx:XML id="xmlDP">

<root>

<node>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</node>

<node>Donec sit amet dui nec pede aliquam auctor.</node>

<node>Integer vestibulum sodales dui.</node>

<node>Sed nonummy ligula et tortor.</node>

<node>Aenean varius neque vel felis.</node>

<node>Phasellus venenatis ipsum sit amet nisi.</node>

<node>Nullam vitae turpis et ipsum cursus venenatis.</node>

<node>Pellentesque tincidunt pede non arcu.</node>

<node>Aliquam ut massa quis ante dignissim egestas.</node>

<node>Curabitur facilisis velit sit amet metus.</node>

<node>Vivamus ornare massa ac massa.</node>

<node>Nam accumsan rutrum purus.</node>

</root>

</mx:XML>



<mx:List id="list"

dataProvider="{xmlDP.node}"

horizontalScrollPolicy="on"

verticalScrollPolicy="auto"

rowCount="6"

width="200" />



</mx:Application>



Creating a tool tip on a Flex TextInput control with password masked text





<mx:TextInput id="ccNumber" text="4111111111111111" displayAsPassword="true" toolTip="{ccNumber.text}" />


<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white">



<mx:Script>

<![CDATA[

import mx.formatters.DateBase;

]]>

</mx:Script>



<mx:Form>

<mx:FormItem label="Name:">

<mx:TextInput id="ccName"

text="JOHN DOE" />

</mx:FormItem>

<mx:FormItem label="Number:">

<mx:TextInput id="ccNumber"

text="4111111111111111"

displayAsPassword="true"

toolTip="{ccNumber.text}" />

</mx:FormItem>

<mx:FormItem label="Type:">

<mx:ComboBox id="ccType"

dataProvider="[American Express,MasterCard,Visa]" />

</mx:FormItem>

<mx:FormItem label="Expiration:" direction="horizontal">

<mx:ComboBox id="ccExpMM"

initialize="ccExpMM.dataProvider = DateBase.monthNamesShort;" />

<mx:ComboBox id="ccExpYYYY"

dataProvider="[2008,2009,2010]" />

</mx:FormItem>

</mx:Form>



</mx:Application>






Creating semi-transparent PopUpButton pop up menus in Flex





<?xml version="1.0" encoding="utf-8"?>


<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="top"

backgroundColor="white">



<mx:Style>

PopUpButton {

popUpStyleName: myCustomPopUpStyleName;

}



.myCustomPopUpStyleName {

fontWeight: normal;

textAlign: left;

backgroundAlpha: 0.4;

backgroundColor: white;

borderStyle: solid;

}

</mx:Style>



<mx:Script>

<![CDATA[

import mx.controls.Menu;



private var menu:Menu;



private function init():void {

menu = new Menu();

menu.labelField = "@label";

menu.dataProvider = xmlList;

popUpButton.popUp = menu;

menu.width = popUpButton.width;

}

]]>

</mx:Script>



<mx:XMLList id="xmlList">

<node label="Alert" />

<node label="Button" />

<node label="ButtonBar" />

<node label="CheckBox" />

<node label="ColorPicker" />

<node label="ComboBox" />

</mx:XMLList>



<mx:ApplicationControlBar dock="true">

<mx:PopUpButton id="popUpButton"

label="Please select an item..."

openAlways="true"

creationComplete="init();" />

</mx:ApplicationControlBar>



<mx:VBox backgroundAlpha="0.5"

backgroundColor="haloSilver"

width="100%"

height="100%" />



</mx:Application>



Adding checkboxes, radiobuttons, and sub-menus to a Flex PopUpButton control’s pop up menu





<?xml version="1.0" encoding="utf-8"?>


<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="top"

backgroundColor="white">



<mx:Style>

PopUpButton {

popUpStyleName: myCustomPopUpStyleName;

}



.myCustomPopUpStyleName {

fontWeight: normal;

textAlign: left;

}

</mx:Style>



<mx:XML id="xmlDP">

<root>

<node label="The quick brown fox jumped over the lazy dog." />

<node label="Lorem ipsum (disabled)." enabled="false" />

<node type="separator" />

<node label="parent">

<node label="child1" />

</node>

<node label="parent (disabled)" enabled="false">

<node label="child1" />

<node label="child2" />

<node label="child3" />

</node>

<node type="separator" />

<node label="type=check" id="ch" type="check" toggled="true" />

<node label="type=check" id="ch" type="check" toggled="true" enabled="false" />

<node type="separator" />

<node label="1) type=radio" type="radio" groupName="radioGroup" toggled="true" />

<node label="2) type=radio" type="radio" groupName="radioGroup" />

<node label="3) type=radio" type="radio" groupName="radioGroup" />

<node label="4) type=radio" type="radio" groupName="radioGroup" enabled="false" />

</root>

</mx:XML>



<mx:Script>

<![CDATA[

import mx.controls.Menu;



private var menu:Menu;



private function init():void {

menu = new Menu();

menu.labelField = "@label";

menu.dataProvider = xmlDP;

menu.showRoot = false;

menu.width = popUpButton.width;

popUpButton.popUp = menu;

}

]]>

</mx:Script>



<mx:PopUpButton id="popUpButton"

label="Please select an item"

openAlways="true"

creationComplete="init();" />



</mx:Application>


January 23, 2008

Embedding and animating fonts in a Flex application

In this example we embed a font (the awesome “Base 02″ PC TrueType font (TTF) from http://www.stereo-type.net/), animate it using the Zoom effect and the Elastic.easeOut easing method. We also set the rotation and alpha properties (which you can’t do with non-embedded fonts), and we set the fontAntiAliasType to “advanced” to give the font a cleaner look. Finally we use the effectEnd event to loop the animation.





<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"

verticalAlign="middle" backgroundColor="white">



<mx:Script>

<![CDATA[

/* Import all the easing classes so its

easier to switch between them on the

fly without tweaking import statements. */

import mx.effects.easing.*;

]]>

</mx:Script>



<mx:Style>

@font-face {

src: url('assets/base02.ttf');

font-family: Base02;

}



.MyEmbeddedFont {

font-family: Base02;

font-size: 16px;

}

</mx:Style>



<!-- Set zoom effect for 2.5 seconds (2500 milliseconds) and use the

Elastic.easeOut easing method. -->

<mx:Zoom id="zoom" duration="2500" easingFunction="Elastic.easeOut"

target="{embeddedText}" />



<!-- Use advanced font anti-aliasing for the embedded font,

set the rotation to 5 degrees, alpha to 80% and loop the animation. -->

<mx:Text id="embeddedText" text="The quick brown fox jumped

over the lazy dog." styleName="MyEmbeddedFont" rotation="5" alpha="0.8"

fontAntiAliasType="advanced"

creationComplete="zoom.play();" effectEnd="zoom.play()" />



</mx:Application>

Specifying certain unicode-ranges for embedded fonts

you want to embed the numbers 0-9, you would click on “0″ and note it’s Unicode value (U+0030), then click on “9″ and do the same (U+0039). Now, in your Flex application, you would specify this range in the @font-family style block like so:




<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white">



<mx:Script>

<![CDATA[

/* Import all the easing classes so its

easier to switch between them on the

fly without tweaking import statements. */

import mx.effects.easing.*;

]]>

</mx:Script>



<mx:Style>

@font-face {

src: url('assets/base02.ttf');

font-family: Base02;

unicode-range:

U+0054-U+0054, /* T */

U+0061-U+007A, /* a-z */

U+002E-U+002E; /* . (period) */

}



.MyEmbeddedFont {

font-family: Base02;

font-size: 14px;

}

</mx:Style>



<!-- Set zoom effect for 2.5 seconds (2500 milliseconds) and use the Elastic.easeOut easing method. -->

<mx:Zoom id="zoom" duration="2500" easingFunction="Elastic.easeOut" target="{embeddedText}" />



<!-- Use advanced font anti-aliasing for the embedded font, set

the rotation to 5 degrees, alpha to 80% and loop the animation. -->

<mx:Text id="embeddedText" text="The quick brown fox jumped over the lazy dog." styleName="MyEmbeddedFont" rotation="5" alpha="0.8" fontAntiAliasType="advanced" creationComplete="zoom.play();" effectEnd="zoom.play()" />

</mx:Application>

Styling the Flex Alert control

This is a more complex version of my previous example. This time in addition to making the Alert control’s text non-selectable, we use an embedded font for the Alert title, message, buttons, as well as edit the drop shadow, remove the rounded corners, and remove the button skins.




<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white"

creationComplete="showAlert()"

applicationComplete="init()">



<!-- Used by the ApplicationControlBar control. -->

<mx:String id="fileName" />

<mx:String id="fileSize" />



<!-- Used by the Alert control. -->

<mx:String id="message">The quick brown fox jumped over the lazy dog.



The quick brown fox jumped over the lazy dog.</mx:String>

<mx:String id="title">The quick brown fox jumped over the lazy dog?</mx:String>



<mx:Script>

<![CDATA[

import mx.controls.Alert;



private var a:Alert;



private function init():void {

var appInfo:LoaderInfo = Application.application.loaderInfo;

/* Just grab the filename from the SWF URL. */

fileName = (appInfo.url).split("/").pop();

/* Convert bytes to kilobytes. */

fileSize = (appInfo.bytesTotal / 1024).toFixed(2);

}



private function showAlert():void {

Alert.yesLabel = "Accept";

Alert.noLabel = "Reject";

Alert.buttonWidth = 120;



a = Alert.show(

message,

title,

Alert.NO | Alert.YES

);

/* Make the Alert form's text non-selectable. */

a.mx_internal::alertForm.mx_internal::textField.selectable = false;

}

]]>

</mx:Script>



<mx:Style>

@font-face{

src: url("./fonts/base02.ttf");

fontFamily: "Base02";

}



Alert {

titleStyleName: "alertTitle";

messageStyleName: "alertMessage";

buttonStyleName: "alertButton";

dropShadowEnabled: true;

shadowDistance: 5;

shadowDirection: right;

cornerRadius: 0;

embedFonts: true;

fontFamily: Base02;

}



.alertTitle {

letterSpacing: 0;

fontSize: 14;

color: red;

}



.alertMessage {

letterSpacing: 0;

fontSize: 10;

fontWeight: normal;

color: black;

}



.alertButton {

letterSpacing: 0;

fontSize: 11;

cornerRadius: 10;

fontWeight: normal;

textRollOverColor: white;

color: red;

skin: ClassReference(null);

}

</mx:Style>



<!-- Display SWF name and file size. -->

<mx:ApplicationControlBar id="applicationControlBar" dock="true">

<mx:Label id="info" text="{fileName} ({fileSize}kb)" />

</mx:ApplicationControlBar>



<!-- Click to launch Alert control. -->

<mx:Button label="Launch Alert" click="showAlert()" />

</mx:Application>

Styling a Flex Button control using embedded fonts

The following example shows how you can customize the appearance of a Flex Button control by using an embedded font and removing the Button’s default skin.






<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

applicationComplete="init()"

layout="vertical"

verticalAlign="middle"

backgroundColor="white">



<mx:String id="fileName" />

<mx:String id="fileSize" />



<mx:Script>

<![CDATA[

private function init():void {

var appInfo:LoaderInfo = Application.application.loaderInfo;

/* Just grab the filename from the SWF URL. */

fileName = (appInfo.url).split("/").pop();

/* Convert bytes to kilobytes. */

fileSize = (appInfo.bytesTotal / 1024).toFixed(2);

}

]]>

</mx:Script>



<mx:Style>

@font-face{

src: url("./fonts/base02.ttf");

fontFamily: "Base02";

}



.myButtonStyle {

embedFonts: true;

fontFamily: Base02;

fontWeight: normal;

fontSize: 24;

cornerRadius: 0;

letterSpacing: 4;

textRollOverColor: red;

skin: ClassReference(null);

icon: Embed(source="./assets/iconInstall.png");

}

</mx:Style>

<mx:ApplicationControlBar id="applicationControlBar" dock="true">

<mx:Label id="info" text="{fileName} ({fileSize}kb)" />

</mx:ApplicationControlBar>

<mx:Button id="btn" label="{btn.getStyle('fontFamily')}" styleName="myButtonStyle" />

</mx:Application>






Styling the HSlider control using CSS

The following example shows how you can style a HSlider (or VSlider) control in Flex using Cascading Style Sheets (CSS).




<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white">



<mx:Style>

@font-face{

src: url("./fonts/arial.ttf");

fontFamily: "ArialEmbedded";

}



.MyLabel {

fontFamily: ArialEmbedded;

fontSize: 15;

fontWeight: normal;

}



.MyDataTip {

backgroundAlpha: 1.0;

backgroundColor: haloBlue;

color: white;

cornerRadius: 10;

fontWeight: bold;

letterSpacing: 1;

}



.MySlider {

dataTipOffset: 0;

dataTipPrecision: 0;

dataTipPlacement: left;

dataTipStyleName: MyDataTip;

showTrackHighlight: true;

labelStyleName: MyLabel;

}

</mx:Style>



<mx:Array id="labelArr">

<mx:Number>-10</mx:Number>

<mx:Number>0</mx:Number>

<mx:Number>10</mx:Number>

<mx:Number>20</mx:Number>

</mx:Array>



<mx:HSlider id="slider"

minimum="-10"

maximum="20"

labels="{labelArr}"

snapInterval="1"

tickInterval="10"

styleName="MySlider" />

</mx:Application>






Embedding fonts by name instead of location

The following example shows how you can embed a font in Flex by specifying the font name instead of a location by using the local() function instead of the src() function when embedding a font.




<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white"

applicationComplete="init();">



<mx:Style>

@font-face {

src:local("Arial");

fontFamily: ArialEmbedded;

}



@font-face {

src:local("Arial");

fontFamily: ArialEmbedded;

fontWeight: bold;

}

</mx:Style>



<mx:Script>

<![CDATA[

private var bTotal:Number;



private function init():void {

bTotal = Application.application.loaderInfo.bytesTotal;

/* Convert from bytes to kilobytes. */

lbl.text = (bTotal / 1024).toFixed(2) + " KB";

}

]]>

</mx:Script>



<mx:ApplicationControlBar dock="true">

<mx:Label id="lbl" />

</mx:ApplicationControlBar>



<mx:ProgressBar id="progressBar"

label="Loading Flex Application"

labelPlacement="center"

fontFamily="ArialEmbedded"

rotation="15"

indeterminate="true"

themeColor="haloSilver" />



</mx:Application>






Embedding fonts from a Flash SWF file into a Flex application

The following examples show how you can embed a font from a Flash SWF into a Flex application using @font-face in a <<:Style />> block, or using the [Embed] metadata.




<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white"

applicationComplete="init()">



<mx:Script>

<![CDATA[

private function init():void {

var appInfo:LoaderInfo = Application.application.loaderInfo;

/* Just grab the filename from the SWF URL. */

var fileName:String = (appInfo.url).split("/").pop();

/* Convert bytes to kilobytes. */

var kbTotal:String = (appInfo.bytesTotal / 1024).toFixed(2);

info.text = fileName + " (" + kbTotal + "kb)";

}

]]>

</mx:Script>



<mx:Style>

@font-face{

src: url('./fonts/fromFlash.swf');

fontFamily: "Myriad Web Pro";

}



.myriadWebProFromSWF {

fontFamily: "Myriad Web Pro";

fontSize: 24;

}

</mx:Style>



<mx:ApplicationControlBar dock="true">

<mx:Label id="info" />

</mx:ApplicationControlBar>

<mx:Text styleName="myriadWebProFromSWF">

<mx:text>The quick brown fox jumped over the lazy dog.</mx:text>

</mx:Text>

</mx:Application>

January 14, 2008

Setting a label’s font weight on a Flex LinkBar and ToggleButtonBar control

The following example shows how you can set the font weight of a label on LinkBar control and ToggleButton control in Flex by setting the linkButtonStyleName style and buttonStyleName style respectively.

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

fontWeight: normal;
}
.myCustomButtonStyleName
{
fontWeight: normal;

}
</mx:Style>
<mx:Array id="arr">
<mx:Object label="One" />
<mx:Object label="Two" />
<mx:Object label="Three" />
<mx:Object label="Four" />

</mx:Array>
<mx:LinkBar id="linkBar" dataProvider="{arr}" linkButtonStyleName="myCustomLinkButtonStyleName" />
<mx:ToggleButtonBar id="toggleButtonBar" dataProvider="{arr}" buttonStyleName="myCustomButtonStyleName" />
</mx:Application>

Or, you can set the styles a bit more globally by using the following snippet:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white">
<mx:Style>
LinkBar
{
linkButtonStyleName: regularFontWeight;
}
ToggleButtonBar
{
buttonStyleName: regularFontWeight;
}
.regularFontWeight { fontWeight: normal;
}
</mx:Style>
<mx:Array id="arr">
<mx:Object label="One" />
<mx:Object label="Two" />
<mx:Object label="Three" />

<mx:Object label="Four" />
</mx:Array>
<mx:LinkBar id="linkBar" dataProvider="{arr}" />
<mx:ToggleButtonBar id="toggleButtonBar" dataProvider="{arr}" />
</mx:Application>

Clearing a selected RadioButton control in Flex

The following example shows how you can use ActionScript to clear a currently selected radio button by setting the RadioButtonGroup class’s selection property to null.

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white">

<mx:Script>

<![CDATA[ import mx.controls.Alert;

private function reset():void

{

answers.selection = null;

}

private function check():void

{

if (answers.selectedValue)

{

Alert.show(answers.selectedValue.toString());

}

else { Alert.show("unselected"); } } ]]>

</mx:Script>

<mx:RadioButtonGroup id="answers" />

<mx:Form backgroundColor="red">

<mx:FormItem>

<mx:Text id="question" text="Question..." />

</mx:FormItem>

<mx:FormItem>

<mx:RadioButton id="answer1" group="{answers}" label="Answer 1" />

</mx:FormItem>

<mx:FormItem>

<mx:RadioButton id="answer2" group="{answers}" label="Answer 2" />

</mx:FormItem>

<mx:FormItem>

<mx:RadioButton id="answer3" group="{answers}" label="Answer 3" />

</mx:FormItem>

<mx:FormItem>

<mx:RadioButton id="answer4" group="{answers}" label="Answer 4" />

</mx:FormItem>

<mx:FormItem>

<mx:RadioButton id="answer5" group="{answers}" label="Answer 5" />

</mx:FormItem>

<mx:FormItem direction="horizontal">

<mx:Button label="Check" click="check();" />

<mx:Button label="Reset" click="reset();" />

</mx:FormItem>

</mx:Form>

</mx:Application>

January 5, 2008

Advanced input filtering with flex

All the time I have been developing web applications in Java I have build my UI upon some framework like Struts, Tapestry or JSF. All of these frameworks encourage serverside validation and to some extend clientside validation.
I haven't seen a web framework facilitating a prober way to do input filtering. The few times I have implemented an inputfilter I have cooked up some javascript to do the job - normally not that reusable.
I don´t see filtering as a substitution of server side validation, but more as an extension of the user experience where the user gets immediate feedback on her use of an application.

At my current project we build the UI on the flash runtime in flex - and the flex framework really brings some interesting opportunities.

Basic
For basic filtering a restrict property can be set on the TextInput component only allowing a subset of characters as input.
But as soon as your inputfilter depends on already entered text the filtering gets a bit more sophisticated :-)

Advanced
On the TextInput you can listen for a TextEvent that contains the data the user is entering as input but react upon it before it actually hits the input field. That gives you the opportunity to prevent the input from reaching the Textinput component by calling the preventDefault() method on the event if the data isn't allowed for some business rule that you apply.

public class FilterTextInput extends TextInput {

public function FilterTextInput () {
addEventListener ( TextEvent . TEXT_INPUT , validateInput );
}

private function validateInput ( event : TextEvent ) : void {
var actualInput : String = EventUtil . getActualText ( event );
trace ( actualInput );
//sample filtering securing that all input characters are unique
if (! StringUtil . containsUniqueChars ( actualInput )) {
event . preventDefault ();
}
}
}
Unfortunately the event only contains the data the user is about to enter. So if you would like to validate the entire input as it would be after when the input is combined with the already entered text, you have to do some work yourself.


EventUtil
I implemented an EventUtil class capable of extracting the actual input as it would look like when the already entered text is combined with the incoming input (the method used in the sample above). The tricky part is to take notice of where in the existing text the new input is about to be entered. The input could replace some existing text and at the same time be pasted into the middle of an existing text.

My utility method looks like this:
public static function getActualText ( event : TextEvent ) : String {
var input : TextInput = TextInput ( event . currentTarget );
var text : String = input . text ;
var b : int = input . selectionBeginIndex ;
var e : int = input . selectionEndIndex ;

var before : String = "" ;
var after : String = "" ;
if ( e > 0 ) {
before = text . substring ( 0 , b );
}
if ( b < text . length ) {
after = text . substring ( e , text . length );
}
return before + event . text + after ;
}

January 1, 2008

Changing the close button skin on a Flex TitleWindow container

The following example shows how you can change the appearance of the close button in a TitleWindow container in Flex by setting the closeButtonSkin style (or the closeButtonUpSkin, closeButtonOverSkin, closeButtonDownSkin, closeButtonDisabledSkin styles individually).

Code Example

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Style> TitleWindow { closeButtonSkin: Embed("cancel.png"); /* Set values from defaults.css to null. */ closeButtonDisabledSkin: ClassReference(null); closeButtonDownSkin: ClassReference(null); closeButtonOverSkin: ClassReference(null); closeButtonUpSkin: ClassReference(null); } </mx:Style> <mx:TitleWindow id="titleWindow" title="TitleWindow" status="status message" showCloseButton="true" width="100%" height="100%" /> </mx:Application>

If you want to use a different image for each state (up, over, down, disabled), you can either set each skin separately, as seen in the following snippet:
<mx:Style> TitleWindow { closeButtonUpSkin: Embed("bullet_green.png"); closeButtonOverSkin: Embed("bullet_yellow.png"); closeButtonDownSkin: Embed("bullet_red.png"); closeButtonDisabledSkin: Embed("bullet_white.png"); } </mx:Style>
Or, you can specify a SWF file and symbol name for the close button skins, as seen in the following snippet:
TitleWindow { closeButtonDisabledSkin: Embed(source="Assets.swf", symbol="CloseButtonDisabled"); closeButtonDownSkin: Embed(source="Assets.swf", symbol="CloseButtonDown"); closeButtonOverSkin: Embed(source="Assets.swf", symbol="CloseButtonOver"); closeButtonUpSkin: Embed(source="Assets.swf", symbol="CloseButtonUp"); }

December 27, 2007

Publish your Flex application code

From Flex builder select project -> Publish application source.

Dialog box for selecting the source elements will open. By default, all project source code and assets are selected, but you can specify at your own.

If the main application is an MXML file, flex builder automatically adds the necessary code to enable the view source context menu item.

If you want to manually enable theat item, you should add the viewSourceURL attribute to the <mx:Application> tag such that it points to the index.html page in the published source code directory.

If the main application is an AS file, you'll have to enable the context menu item using AS code. this step requires the com.adobe.viewsource.ViewSource class .You should then call the static addMenuItem() method , passing it a reference to the main class instance and the URL for the source code, like so:

ViewSource.addMenuItem(this,”sourcecode/index.html”);


Popup in Flex

CanvasPopup.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<!– We are creating a TitleWindow so that it would be draggable–>
<mx:TitleWindow xmlns:mx=”
http://www.adobe.com/2006/mxml ” width=”252″ height=”200″>
<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;
public function closeThis():void
{
PopUpManager.removePopUp(this);
}
]]>
</mx:Script>
<mx:Button x=”500″ y=”150″ label=”Close” click=”closeThis()”/>
</mx:TitleWindow>

popup.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” width=”100%” height=”100%”>
<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;
public function showPopUp():void
{
var pop2:CanvasPopup = CanvasPopup(PopUpManager.createPopUp(this,CanvasPopup,true));
PopUpManager.centerPopUp(pop2);
}
]]>
</mx:Script>
<mx:Canvas>
<mx:Button x=”313″ y=”229″ label=”Show Popup” click=”showPopUp()”/>
</mx:Canvas>
</mx:Application>

Through Actionscript

CanvasPopup.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:TitleWindow xmlns:mx=”
http://www.adobe.com/2006/mxml ” width=”252″ height=”200″ initialize=”init()”>
<mx:Script>
<![CDATA[
import mx.controls.Button;
import mx.controls.Alert;
import mx.managers.PopUpManager;
import flash.events.MouseEvent;
private function closeThis(e:MouseEvent):void
{
PopUpManager.removePopUp(this);
}
private function init():void{
var btn:Button = new Button()
btn.move(500,150);
btn.label=”Close”;
btn.addEventListener(MouseEvent.CLICK,closeThis);
addChild(btn);
}
]]>
</mx:Script>
</mx:TitleWindow>

popup.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” width=”100%” height=”100%” initialize=”init()”>
<mx:Script>
<![CDATA[
import mx.controls.Button;
import mx.managers.PopUpManager;
import flash.events.MouseEvent;
private function showPopUp(e:MouseEvent):void
{
var pop2:CanvasPopup = CanvasPopup(PopUpManager.createPopUp(this,CanvasPopup,true));
PopUpManager.centerPopUp(pop2);
}
private function init():void{
var btn:Button=new Button()
btn.move(313,229);
btn.label=”Show Popup”;
btn.addEventListener(MouseEvent.CLICK, showPopUp);
addChild(btn);
}
]]>
</mx:Script>
</mx:Application>


Related Flex Tutorials