Archive for June, 2008

26
Jun

Changing the text alignment of a List control in Flex

The following example shows how you can change the text alignment in a Flex List control by setting the textAlign style.

Full code after the jump.

<?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:Object label="Five" />
<mx:Object label="Six" />
</mx:Array>

<mx:ApplicationControlBar dock="true">
<mx:Form styleName="plain">
<mx:FormItem label="textAlign:">
<mx:ComboBox id="comboBox"
dataProvider="[left,center,right]" />
</mx:FormItem>
</mx:Form>
</mx:ApplicationControlBar>

<mx:List id="list"
dataProvider="{arr}"
textAlign="{comboBox.selectedItem}"
width="100" />

</mx:Application>



																
26
Jun

Using an embedded font with the ComboBox control 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>
@font-face {
src: local("Base 02");
fontFamily: EmbeddedBase02;
fontWeight: bold;
}

@font-face {
src: local("Base 02");
fontFamily: EmbeddedBase02;
}
</mx:Style>

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

<mx:ComboBox id="comboBox"
dataProvider="{arr}"
fontFamily="EmbeddedBase02" />

</mx:Application>



																
26
Jun

Setting a prompt on a ComboBox control 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:Array id="arr">
<mx:Object abbrev="AL" name="Alabama" />
<mx:Object abbrev="AK" name="Alaska" />
<mx:Object abbrev="AZ" name="Arizona" />
<mx:Object abbrev="AR" name="Arkansas" />
<mx:Object abbrev="CA" name="California" />
<mx:Object abbrev="CO" name="Colorado" />
<mx:Object abbrev="CT" name="Connecticut" />
</mx:Array>

<mx:ApplicationControlBar dock="true">
<mx:Button id="button"
label="Reset ComboBox"
click="comboBox.selectedIndex = -1;" />
</mx:ApplicationControlBar>

<mx:ComboBox id="comboBox"
dataProvider="{arr}"
labelField="name"
prompt="Please select a state..." />

</mx:Application>

View source is enabled in the following example.

Due to popular demand, here is the “same” example in a more ActionScript friendly format:

View MXML

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

<mx:Script>
<![CDATA[
import mx.controls.ComboBox;
import mx.controls.Button;
import mx.containers.ApplicationControlBar;

private var arr:Array;
private var appControlBar:ApplicationControlBar;
private var button:Button;
private var comboBox:ComboBox;

private function init():void {
arr = [];
arr.push({abbrev:"AL", name:"Alabama"});
arr.push({abbrev:"AK", name:"Alaska"});
arr.push({abbrev:"AZ", name:"Arizona"});
arr.push({abbrev:"AR", name:"Arkansas"});
arr.push({abbrev:"CA", name:"California"});
arr.push({abbrev:"CO", name:"Colorado"});
arr.push({abbrev:"CT", name:"Connecticut"});

button = new Button();
button.label = "Reset ComboBox";
button.addEventListener(MouseEvent.CLICK, button_click);

appControlBar = new ApplicationControlBar();
appControlBar.dock = true;
appControlBar.addChild(button);
Application.application.addChildAt(appControlBar, 0);

comboBox = new ComboBox();
comboBox.dataProvider = arr;
comboBox.labelField = "name";
comboBox.prompt = "Please select a state...";
addChild(comboBox);
}

private function button_click(evt:MouseEvent):void {
comboBox.selectedIndex = -1;
}
]]>
</mx:Script>

</mx:Application>
24
Jun

Building Modular Flex Applications

The needs to break up large application code and reuse code across many applications are key factors that led Adobe to spend the time providing classes that help make creating modular applications very easy. Splitting up an application into separate modular SWFs that can be loaded and unloaded by an application is similar to Runtime Shared Libraries (RSLs). The difference is that RSLs are statically linked at compile time, and module SWFs are loaded at run-time. This allows for smaller initial download sizes and short load times for applications. There is a slight overhead incurred by breaking up the SWFs and loading them separately, but the total size of all the modules compared to a single SWF application is a nominal increase of size.

The new classes provided in the mx.modules package make everything happen. Each module SWF is required to extend the mx.modules.ModuleBase class, typically done by creating a new MXML file with a root tag of <mx:Module>. The following example shows a application loading and unloading modules with the help of a button. Listing A-7 is the main application, and Listing A-8, Listing A-9, and Listing A-10 are the three modules called RuntimeCSSModule, DateWidget, and PowWidget. The first two modules are loaded when the application is first loaded. After the application is loaded, the user proceeds to click the button. Each button click event calls a method that switches between loading/unloading the RuntimeCSSModule and DateWidget and loading/unloading the PowWidget. Continue reading ‘Building Modular Flex Applications’

24
Jun

Flex ASDoc Tool

The Adobe Flex 2 Language Reference documentation found on the Adobe Web site was created with a tool called ASDoc. Flex 2.0.1 provides developers the ASDoc command-line tool to create documentation for their own components and classes. The command-line executable is called asdoc and is located in the bin directory, along with the mxmlc and compc compilers. The tool generates HTML files that describe package, property, method, and other class information through syntax written as comments in the code. The syntax uses a number of specific ASDoc tags to tell asdoc how to generate the documentation.

ASDoc Tags and Syntax

The following table lists the tags used in this appendix’s example code. The example logging code created in Chapter 19 will be modified to demonstrate ASDoc’s capabilities.

Open table as spreadsheet

ASDoc Tag Syntax Description
/**

*/

Comment the block starting with /** and ending with */.

This syntax tells ASDoc to read text and tags inside the command block.

/** Text wrapped in a comment block not preceded by a tag will be read as the main description.
<p></p> Used for each description paragraph that precedes the first paragraph.
<code></code> Used around text inside the comment blocks to define a specific style for the ASDoc to output for that specific text.
@private The specific code will not be included in the ASDoc output.
@param paramName description Defines descriptions for each parameter in the method. You can declare multiple @param values in a code block.
@default value The text describing the default value for the property.
@see classname [display text] The classname defines other classes in the documentation that will be linked. ASDoc puts output under the “See also” area.
@return description Description of the value the method will return.

Documenting the Logger Classes

Follow these steps to learn about the process of documenting classes:

  1. Open Adobe Flex Builder 2.
  2. Create a new Flex Basic Project and call it ProfessionalFlexLogging.
  3. Create the following folders in the root of the project:
    1. /professional/
    2. /professional/flex2/
    3. /professional/flex2/logging/
  1. Copy the following files from Chapter 19 and Chapter 27 into the /professional/flex2/logging/ folder:
    1. LocalConnectionTraceTarget.as
    2. LogController.mxml
    3. TracePanel.mxml
    4. TracePanelTarget.as
  1. Copy the CustomLoggerMain.mxml file into the root of the project.

  2. Open CustomLoggerMain.mxml and change the following line of code:
    xmlns:logger="*"

    to

    xmlns:logger="professional.flex2.logging.*"
  3. Open LocalConnectionTraceTarget.as and change package to package professional.flex2.logging.
  4. Open TracePanelTarget.as and change package to package professional.flex2.logging.

The next code snippet outlines code examples highlighting ASDoc comment syntax. The full code listings are located later in the appendix. To start, open the TracePanelTarget.as file and add the following comment block to the constructor method:

...
/**
*      Constructor.
*
*      @param console Reference to a <code>TextArea</code>
*                 object that will display the output
*                of the messages.
*/
public function TracePanelTarget( console:TextArea ) {
super();
this.console = console;
}
...

The first block of text will be picked up as the first paragraph. The @param tag defines the parameter of the constructor. The best way to see what the comment syntax does is to compile the documentation and see what it looks like. Continue on to the next section to learn how to use the asdoc compiler. The second part of learning how to document the logger classes continues in the section after that, “Documenting the Logger Classes – Continued“.

Using the ASDoc Compiler

The ASDoc tool is a command-line tool with multiple compile arguments. The important ones to understand are -doc-sources, -doc-classes, and -source-path. The first two give you two options for compiling the documentation, by source file or by class name. If you navigate to the ProfessionalFlexLogging Flex Project created earlier in the appendix, the following are available source files:

  • CustomLoggerMain.mxml
  • /professional/flex2/logging/LocalConnectionTraceTarget.as
  • /professional/flex2/logging/LogController.mxml
  • /professional/flex2/logging/TracePanel.mxml
  • /professional/flex2/logging/TracePanelTarget.as

You would use the full name or directory pattern syntax to determine the value of -doc-sources. The following are the comparable class names:

  • CustomLoggerMain
  • professional.flex2.logging.LocalConnectionTraceTarget
  • professional.flex2.logging.LogController
  • professional.flex2.logging.TracePanel
  • professional.flex2.logging.TracePanelTarget

When configured to compile a specific class, the ASDoc tool will also compile all the classes that it references. Finally, the -source-path is needed to tell the ASDoc where to start looking for source files. The -source-path compile argument is like class path values used in other compilers. To run the following example asdoc command-line calls, open up a command prompt and navigate to the ProfessionalFlexLogging project folder on the file system:

// Output set to docs folder
// Create documentation for class CustomLoggerMain
// Classpath set to ./ or the same folder
asdoc -output docs -doc-classes CustomLoggerMain -source-path ./

// Output set to targets folder
// Create documentation for the two Target classes
asdoc -output targets -doc-classes professional.flex2.logging
.LocalConnectionTraceTarget professional.flex2.logging
.TracePanelTarget -source-path ./

// Output set to logging folder
// Create documentation for all sources files under the professional folder
//  this will not pick up CustomLoggerMain
asdoc -output logging -doc-sources ./professional/ -source-path

Documenting the Logger Classes – Continued

You are equipped to create the documentation for TracePanelTarget.as and view how the comments look in the outputted HTML. Run the following command:

asdoc -output docs -doc-classes professional.flex2.logging.TracePanelTarget
-source-path ./

Open up the index.html in a browser. The index.html is located in the docs folder that the ASDoc tool created.

The ASDoc tool does provide limited ability to document MXML files as well. The comment syntax blocks are constrained to being processed inside the <mx:Script></mx:Script> code tags of an MXML file. Open up the TracePanel.mxml file and add the following ASDoc comments:

...
/**
*  Property used in connection with Popup functionality.
*  The value defines the popup state of the control.
*
*  @default false
*/
public var isOpen:Boolean = false;
...

The @default comment tag is used to document that the isOpen property is defaulted to false. Run asdoc on the whole project by using the following command and see the results:

asdoc -output docs -doc-classes CustomLoggerMain -source-path ./

Open up the index.html and click the TracePanel class located in the panels on the left. You’ll find the isOpen property detail containing the following text: “The default value is false.” You can now add more documentation comments and view the results. Listing A-4, Listing A-5, and Listing A-6 show the source files implemented with ASDoc comments. Copy the source files over to your project and play with different comment tag syntaxes.

Listing A-4: LocalConnectionTraceTarget.as

Image from book
package professional.flex2.logging
{

import flash.events.StatusEvent;
import flash.net.LocalConnection;

import mx.controls.TextArea;
import mx.core.mx_internal;

import mx.logging.ILogger;
import mx.logging.LogEvent;
import mx.logging.targets.LineFormattedTarget;

use namespace mx_internal;

/**
* The <code>LocalConnectionTraceTarget</code> extends the
* <code>LineFormattedTarget</code> class to provide
* a basic output mechanism.  This target uses
* <code>LocalConnection</code> to output the trace
* messages to any other application using
* <code>LocalConnection</code> listening on
* <code>_flex2tracepanel</code>.
*
* @see mx.logging.targets.LineFormattedTarget
*/
public class LocalConnectionTraceTarget extends LineFormattedTarget {

/**
*  Constructor.
*/
public function LocalConnectionTraceTarget() {
super();

lc = new LocalConnection();
lc.addEventListener(StatusEvent.STATUS, statusEventHandler);
}

/**
*  @private
*/
private var lc:LocalConnection;

/**
*  @private
*  @internal Need to keep Flex 2 from throwing unhandled
*        status errors
*/
private function statusEventHandler(event:StatusEvent):void {
; // Handles Event Status Calls
}

/**
*  The <code>internalLog</code> method handles the
*  sending of messages.
*
*  @param event <code>LogEvent</code> sent to a
*         <code>ILogger</code> from the <code>Log</code> class.
*/
override public function logEvent(event:LogEvent):void
{
var level:int = event.level;

var date:String = ""
if (includeDate || includeTime)
{
var d:Date = new Date();
if (includeDate)
{
date = Number(d.getUTCMonth() + 1).toString() + "/" +
d.getUTCDate().toString() + "/" +
d.getUTCFullYear() + fieldSeparator;
}
if (includeTime)
{
date = pad(d.getUTCHours()) + ":" +
pad(d.getUTCMinutes()) + ":" +
pad(d.getUTCSeconds()) + "." +
pad(d.getUTCMilliseconds()) + fieldSeparator;
}
}

var category:String = includeCategory ?
ILogger(event.target).category + fieldSeparator : "";

// Connection and Method specific to C# .Net applicaton Flex2TracePanel
lc.send( "_flex2tracepanel", "logMessage", date + category + event.message,
level);
}

/**
*  The pad method adds leading 0's to single digit numbers.
*
*  @return The string representation of two digit leading 0 number.
*/
private function pad(num:Number):String
{
return num > 9 ? num.toString() : "0" + num.toString();
}

}
}
Image from book

Listing A-5: TracePanelTarget.as

Image from book
package professional.flex2.logging
{

import mx.core.mx_internal;
import mx.controls.TextArea;
import mx.logging.targets.LineFormattedTarget;

use namespace mx_internal;

/**
* The <code>TracePanelTarget</code> extends the
* <code>LineFormattedTarget</code> class to provide
* a basic output mechanism.  This target requires a
* reference to a <code>TextArea</code> object. The
* <code>TracePanelTarget</code> uses the reference to
* the <code>TextArea</code> object to output message
* line by line.
*
* @see mx.logging.targets.LineFormattedTarget
*/
public class TracePanelTarget extends LineFormattedTarget {

/**
*  Constructor.
*
*  @param console Reference to a <code>TextArea</code>
*           object that will display the output
*           of the messages.
*/
public function TracePanelTarget( console:TextArea ) {
super();
this.console = console;
}

/**
*  @private
*/
private var console:TextArea;

/**
*  The <code>internalLog</code> method handles the
*  sending of messages.
*
*  @param message The message to be logged by this target.
*/
override mx_internal function internalLog(message:String):void
{
console.text += message + "\n";
}

}
}
Image from book

Listing A-6: TracePanel.as

Image from book
<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml"
title="Trace Panel"
paddingBottom="10" paddingLeft="10"
paddingRight="10" paddingTop="10"
minHeight="360"
minWidth="400"
initialize="init()"
showCloseButton="true"
close="close()"
layout="vertical">
<mx:Script>
<![CDATA[
import mx.logging.Log;
import mx.logging.LogEventLevel;
import mx.collections.ArrayCollection;
import mx.managers.PopUpManager;

/**
*  Property used in connection with Popup functionality.
*  The value defines the popup state of the control.
*
*  @default false
*/
public var isOpen:Boolean = false;

/**
*  @private
*/
[Bindable]
private var targets:ArrayCollection;

/**
*  @private
*/
private var target:TracePanelTarget;

/**
*  @private
*/
private var target2:LocalConnectionTraceTarget;

/**
*  @private
*/
private function init():void
{
target = new TracePanelTarget( txtOutput );
target.filters=["*"];
target.level = LogEventLevel.ALL;
target.includeDate = true;
target.includeCategory = true;
target.includeLevel = true;

target2 = new LocalConnectionTraceTarget();
target2.filters=["*"];
target2.level = LogEventLevel.ALL;

Log.getLogger( "TracePanel" ).debug( "initialization" );
}

/**
*  @private
*/
private function close():void
{
isOpen = false;
PopUpManager.removePopUp( this );
}

/**
*  @private
*/
private function changeTarget():void
{
if( !chkFlag.selected ) {
Log.addTarget( target );
Log.getLogger( "TracePanel" ).info( "Turned logging on!" );
} else {
Log.getLogger( "TracePanel" ).info( "Turning logging off!" );
Log.removeTarget( target );
}
}

/**
*  @private
*/
private function changeFlex2Target():void
{
if( !chkFlex2TracePanel.selected ) {
Log.addTarget( target2 );
Log.getLogger( "TracePanel" ).info( "Turned logging on!" );
} else {
Log.getLogger( "TracePanel" ).info( "Turning logging off!" );
Log.removeTarget( target2 );
}
}

/**
*  @private
*/
private function filterTarget():void
{
Log.getLogger( "TracePanel" ).info( "Filter change!" );
Log.removeTarget( target );
Log.removeTarget( target2 );
target.filters = idFilter.text.split( "," );
if( target.filters == null )
target.filters = ["*"];
target2.filters = idFilter.text.split( "," );
if( target2.filters == null )
target2.filters = ["*"];
Log.addTarget( target );
Log.addTarget( target2 );
}

]]>
</mx:Script>

<mx:Form>
<mx:FormItem label="Filter Categories:">
<mx:TextInput
id="idFilter"
text="*"
change="filterTarget()" />
</mx:FormItem>
<mx:FormItem label="Turn Local Logging Off:">
<mx:CheckBox
id="chkFlag"
selected="false"
change="changeTarget()" />
</mx:FormItem>
<mx:FormItem label="Turn Flex2 Trace Panel Logging Off:">
<mx:CheckBox
id="chkFlex2TracePanel"
selected="false"
change="changeFlex2Target()" />
</mx:FormItem>
</mx:Form>
<mx:HBox
width="100%"
horizontalAlign="center">
<mx:Button
label="Clear Output"
click="txtOutput.text = ''" />
</mx:HBox>
<mx:Label
text="Output Console" />
<mx:TextArea
id="txtOutput"
updateComplete="txtOutput.verticalScrollPosition =
txtOutput.maxVerticalScrollPosition + 1;"
width="100%" height="100%" />
</mx:TitleWindow>
Image from book
Tip The best way to find examples of ASDoc comment syntax and usage is to look at the Flex Framework source files.

To go beyond just basic documentation creation, ASDoc provides a list of optional command-line arguments. These options provide functionality to customize the documentation and metadata. To obtain a list of available options, enter the following at the command prompt:

asdoc -help -list or asdoc -help -advanced


Get Adobe Flash playerPlugin by wpburn.com wordpress themes