JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Flex 4.x – Overview

August 22, 2011 by Krishna Srinivasan Leave a Comment

Type of technology

Flex is a highly productive, free open source framework available for building and maintaining web applications which deploy consistently on major browsers, desktops and operating systems.

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

Look and Feel

Drag and Drop

The support for drag and drop can be added for all Flex components. Flex includes built-in support for drag-and-drop operation for some controls such as List, Tree and DataGrid, This automates processing required to support drag and drop operation. Drag-and-drop operation has 3 main stages: initiation, dragging, and dropping. A drag-and-drop operation will either copy or move data from drag initiator to drop target. On successful drop, Flex adds the data to drop target and, optionally, deletes it in case of a move from the drag initiator.

Type of Technology

Adobe Flex is a collection of technologies based on Adobe Flash platform. Currently Adobe Flex applications are build using Flex 3 SDK. Other technologies used with it are Livecycle Data Services (J2EE application integration). Flex applications are viewed on Adobe Flash Player.

Application architecture

Most of the web applications are usually build in MVC architecture in the case of a Flex RIA. The Controller can take form of the Service (or business object) on the application server which reads and updates a Database (the Model).When it receives the requests from the Flex application and itself, represents the Database records to the user.

Environment

For render response in terms of web pages, it requires a browser having Adobe Flash plugin installed on the client machine. For deployment purpose Flex 3 SDK is required on the server machine.

Tools Availability

Flash Builder 4 is the IDE for developing a Flex application. It has end to end support for building a Flex application, component etc. It has all the components given in palettes to that the designing of front end becomes very easy. However, flex application can be written in any text based tool and executed on machine having Flex 3 SDK.

Community Support

Since Flex is a very popular framework for developing RIAs, a huge community support is available. One very popular among them is CFLEX (Community Adobe Flex). This community is dedicated to Adobe Flex.

Frameworks supported

In Flex you have several options to choose for back-end server software (ranging from JEE to Dotnet etc). Few examples are –

  • Flex with Struts:

    With Flex, you can provide a rich front end to your Struts applications. There are two approaches for integrating Flex with Struts application which are based on 2 different ways a Flex application communicates with remote systems i.e. By using the traditional HTTP request/response mechanism or by using SOAP to invoke methods on remote services. Basically Flex can be taken as part of the View in a distributed MVC framework.
  • Flex with Spring:

    This integration is done with the help of Flex Data services i.e. BlazeDS. The BlazeDS adds Remoting Service, Message Service, and Proxy Service to the Flex application. Using Remoting Service a Flex application directly invokes methods of Java objects deployed in the application server. Spring beans are Java objects and so can be accessed using the remoting service of BlazeDS. BlazeDS supports the concept of a factory to configure the Spring container for instantiating Spring beans. The role of the factory is simply to provide ready to use instances of components for BlazeDS (instead of letting BlazeDS instantiate these components).
  • Flex with Ruby on Rails:

    Using this we can do more with very less code. Using Flex we can create the user interface for displaying data. Then we can design this user interface using Flex components for nice look and feel. Then setup the corresponding rails application. Flex can then talk to rails by using the HTTPService to call the different methods in your Rails application.

Animation/ Multimedia support

Flex is developed by Adobe Systems and so is closely related to Flash. Both Flash and Flex Work using ActionScript 3.0, both outputs a SWF format, and both of them use Flash Player to display their content. But Flash is good in animation and Flex by contrast is best at the developing applications and things that are associated with it—charting, handling data, and such. So, Flex can focuses on animations such as transitions that place as menus expand, or items such as image scaling to different sizes and in different states. To add more animation capability we can integrate Flash and Flex in three ways: By using Flash for creating skins and component animations, by adding complex timeline animations, and by adding in Flash multimedia clips that can be controlled in Flex.

Ease of testing

Flex Builder comes with debugging tools which helps in unit testing of a Flex application. Breakpoints can be set both in ActionScript as well as in MXML code that allow application execution to pause at a specified code location. Flex 3 comes with an option of profiling the application. The profiler helps in identifying the performance bottlenecks and memory leaks in the application. It tells about Call frequency, Method duration, Call stacks, Number of instances, Object size and Garbage collection. Apart from these many external tools are available for testing flex application like FlexMonkey, FunFx, QuickTestProfessional etc

Flexibility and Scalability

Flex application is backend agnostic and can work with any kind of backend server till it sends and receive data in the format/protocol supported by Flex. Scalability of Flex application basically depends upon the underlying application server. The Flex application scales upto the level of support provided by the application server.

Browsers dependence

Flex is doesn’t directly depend on the type of browser but is dependent on the Flash Player web browser plug-in. But as per the statistics 98% of browsers available currently have Flash Player plug-in with version 7-9 installed. So, a Flex-generated code works on each client regardless of browser/platform. So, flex has a limitation in this respect that they are limited by the constraints of Flash Player and cannot display anything outside the boundaries of the player’s space embedded in the web page.

Network performance

The Flex client-side processing model and configuration ability helps in improving the network performance. For example, the network bandwidth and connections can be improved by embedding the product images within the SWF file. The SWF file would increase to 60K (or, a total size of 260K), but the application would require 15 fewer network connections to the server. A second potential improvement is to disable the Flex history management feature if it is not required; this prevents the Flex application from transmitting the history management HTML page, thereby reducing network overhead. (Source: Macromedia White Paper, Flex Performance Brief: A Comparison of Flex and Java Server Pages Applications May 2004)

Client Performance

Flex offers the ability to create Rich Internet Applications (RIAs). Misusing this power can result in areas of poor performance. Flex is like any other programming model because certain coding practices can be detrimental to the overall performance of the client. So, depending upon the coding techniques follow are affected at client side:

  • Startup time
  • Playing complex effects smoothly
  • Performance of charting components
  • Streaming of multimedia content

Client Validation Support

As we know, Flex is best used for good user interface. The data that user enters in user interface control might or might not be appropriate for our application. Adobe Flex applications, uses a validator to ensure that values in the fields of the form meet certain criteria.

Flex includes some set of validators for common types of user input datas, such as zip code, phone numbers, and credit card numbers etc. Validators are created in MXML by using a validator tag such asor. Validators uses following 2 properties to specify the item which needs to be validated:

  • source: This specifies the object which contains the property to be validated .We can set this for an instance of a component or to a data model. You can use data binding syntax in MXML for specifying the value for the source property.
  • property: A String that specifies the name of the source property that contains value to validate. This property support dot-delimited Strings for specifying nested properties.

Filed Under: Adobe Flex Tagged With: Adobe Flex 4.0

Creating a Custom Pie Chart Component with Degrafa using Flex

July 31, 2011 by Krishna Srinivasan Leave a Comment

This article is based on Flex on Java , published on October 2010. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ Use promotional code ‘java40beat’ and get 40% discount on eBooks and pBooks ]

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

Creating a Custom Pie Chart Component with Degrafa

Adobe provides data visualization components, but only when you purchase a license for the professional version of the Flash Builder IDE. Because our goal is to do Flex development using only free and open source technologies, we’ve decided to create our own visualization components—besides, it’s more fun.

Drawing in Flex

Flex and Flash provide powerful drawing libraries that we could leverage to create our custom graph components, but we’re going to leverage an open source graphics library called Degrafa. Using Degrafa gives us the ability to declaratively build our graphing components rather than having to deal with the complex calculations involved in drawing pie chart slices as illustrated in listing 1, which shows an example ActionScript class specifically for drawing a pie chart slice found at http://www.adobe.com/devnet/flash/articles/adv_draw_methods.html. Notice how much trigonometry is involved in creating something as simple as a pie chart slice from scratch.

Listing 1 Example of drawing in ActionScript
[code lang=”java”] /*————————————————————-
mc.drawWedge is a method for drawing pie shaped
wedges. Very useful for creating charts. Special
thanks to: Robert Penner, Eric Mueller and Michael
Hurwicz for their contributions.
————————————————————-*/
MovieClip.prototype.drawWedge = function(x, y, startAngle, arc,
radius, yRadius) {
==============
// mc.drawWedge() – by Ric Ewing (ric@formequalsfunction.com) –
version 1.3 – 6.12.2002
//
// x, y = center point of the wedge.
// startAngle = starting angle in degrees.
// arc = sweep of the wedge. Negative values draw clockwise.
// radius = radius of wedge. If [optional] yRadius is defined,
then radius is the x radius.
// yRadius = [optional] y radius for wedge.
// ==============
// Thanks to: Robert Penner, Eric Mueller and Michael Hurwicz
for their contributions.
// ==============
if (arguments.length<5) {
return;
}
// move to x,y position
this.moveTo(x, y);
// if yRadius is undefined, yRadius = radius
if (yRadius == undefined) {
yRadius = radius;
}
// Init vars
var segAngle, theta, angle, angleMid, segs, ax, ay, bx, by, cx, cy;
// limit sweep to reasonable numbers
if (Math.abs(arc)>360) {
arc = 360;
}
// Flash uses 8 segments per circle, to match that, draw in a maximum
// of 45 degree segments. First calculate how many segments are needed
// for our arc.
segs = Math.ceil(Math.abs(arc)/45);
// Now calculate the sweep of each segment.
segAngle = arc/segs;
// The math requires radians rather than degrees. To convert from degrees
// use the formula (degrees/180)*Math.PI to get radians.
theta = -(segAngle/180)*Math.PI;
// convert angle startAngle to radians
angle = -(startAngle/180)*Math.PI;
// draw the curve in segments no larger than 45 degrees.
if (segs>0) {
// draw a line from the center to the start of the curve
ax = x+Math.cos(startAngle/180*Math.PI)*radius;
ay = y+Math.sin(-startAngle/180*Math.PI)*yRadius;
this.lineTo(ax, ay);
// Loop for drawing curve segments
for (var i = 0; i<segs; i++) {
angle += theta;
angleMid = angle-(theta/2);
bx = x+Math.cos(angle)*radius;
by = y+Math.sin(angle)*yRadius;
cx = x+Math.cos(angleMid)*(radius/Math.cos(theta/2));
cy = y+Math.sin(angleMid)*(yRadius/Math.cos(theta/2));
this.curveTo(cx, cy, bx, by);
}
// close the wedge by drawing a line to the center
this.lineTo(x, y);
}
};[/code]
Adobe has released the specifications for its declarative graphics library, called FXG. It appears that the Degrafa team has collaborated with the Adobe team to create this specification, but the FXG functionality is only a subset of what is available from the Degrafa library. This may be a library to keep your eye on as it’s being developed.

Common Degrafa concepts

Before diving into developing the component, let’s familiarize ourselves with some of the terms and concepts that we’ll see as we work through this example.

  • Surface—This is the base component for everything you’ll do in Degrafa. All other Degrafa components will be composed within a Surface.
  • GeometryGroup—After the Surface, this is the next level of composition. The GeometryGroup tag allows you to group Degrafa components to compose an object.
  • Stroke—Stroke is the object that is used to define the look of an object’s outline, in terms of color, thickness, and style. Degrafa provides different Stroke objects for your use depending on the style of stroke you want: SolidStroke, Linear-Gradient, and RadialGradient.
  • Fill—Fill refers to the appearance of the bounded area of a graphical component. Degrafa provides the
    following fills: SolidFill, LinearGradient, Radial-Gradient, BitmapFill, BlendFill, and ComplexFill.
  • Shapes—Degrafa supports drawing many different shapes out of the box, such as Circle, Ellipse, RegularRectangle, RoundedRectangle, Polygon, and more. For irregular shapes, Degrafa also has an extensive library of auto shapes and enables defining any shape you’d like by providing a Scalable Vector Graphics (SVG) path.
  • Repeaters—This gives you the ability to repeat a shape any number of times on the surface.

Much like other Flex components, the Degrafa components are considered either container components, meaning they will contain other Degrafa components, or graphical elements. Figure 1 shows the relationship of the common components.

We’re only going to scratch the surface; to learn more about Degrafa, you can start with the Foundation section of the documentation at http://www.degrafa.org/samples/foundation.html.

Creating a pie chart for fun and profit

Now that we have some of the basic concepts, let’s get on with the task of creating a custom pie chart component. We were inspired by a blog posting by Derrick Grigg titled appropriately enough Degrafa Pie Chart, which can be found at http://www.dgrigg.com/post.cfm/04/15/2008/Degrafa-Pie-Chart. After we decomposed it and removed some of the extra visual effects such as tweening and gradients, it barely resembles what we started with. Figure 2 shows a mock-up of the chart we’ll be developing in this article.

For this example you’ll be developing only a single pie chart component, but some of the concepts illustrated here could potentially be applied to creating any number of charting components.

The component you’ll develop is a combination of a pie chart and a data grid, which will serve the purpose of a legend for the pie chart. Without this it may be difficult for someone looking at the chart to differentiate between data points on the graph. The pie chart will consist of the pie chart itself and another component for each of the slices that make up the chart. You’ll also develop a simple custom ItemRenderer for the chart legend to draw a simple box inside one of the cells in the data grid.

You’ll also be adding a label and a combo box to the GraphView to allow the user to change the data the chart shows. By changing the value of the combo box the user can show how many issues there are by project, type, status, or severity.

New custom event

We’re going to create a new custom event for our pie chart. The reason we’re creating a new one is that if we ever wanted to put more than one pie chart component into our application, we’d need to be able to distinguish which component fired the event.

Listing 2 PieChartEvent.as
[code lang=”java”] package org.foj.event {
import flash.events.Event;
public class PieChartEvent extends Event{
public static const DATA_PROVIDER_UPDATED:String =
"dataProviderUpdated";
public var data:*;
public var id:*; #1
public function PieChartEvent(type : String,
bubbles : Boolean = true,
cancelable : Boolean = false)
{
super(type, bubbles, cancelable);
}
}
}
#1 id property[/code]
This event differs from the one created previously in the addition of an id property (#1). This is done so that the presenter can decide whether or not it needs to react to the event. With the new event created, you can move on to creating the component itself.

PieChart component

First, you’ll develop the view that contains the pie chart and legend. You’ll create these view components in a new package, so create a file named PieChart.mxml in the org.foj.components package of your project. The following listing shows the first part of the code for the PieChart view.

Listing 3 PieChart.mxml
[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
xmlns:degrafa="http://www.degrafa.com/2007"
creationComplete="init()"> #1
<s:layout> #2
<s:HorizontalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import mx.collections.ICollectionView;
import org.foj.event.EventDispatcherFactory;
import org.foj.event.PieChartEvent;
import org.foj.presenter.PieChartPresenter;
private var _presenter:PieChartPresenter; #3
private var _dataProvider:ICollectionView; #4
private function init():void
{
_presenter = new PieChartPresente r(this, id); #5
}
public function set dataProvider(dataProvider:ICollectionView):void { #6
var refreshEvent:PieChartEvent =
new PieChartEvent(PieChartEvent.DATA_PROVIDER_UPDATED);
refreshEvent.id = id;
refreshEvent.data = dataProvider;
EventDispatcherFactory.getEventDispatcher().dispatchEvent(refreshEvent);
}
]]>
</fx:Script>
…
</s:Group>
#1 CreationComplete handler
#2 HorizontalLayout
#3 Define presenter field
#4 Define data provider field
#5 Pass component’s id to presenter
#6 Set property for data provider[/code]
You set the creationComplete event (#1) to call the init method. Next, you set the layout of your component to use HorizontalLayout (#2). Then, you declare a couple of private member variables for the data provider and its presenter (#3, #4).

Inside the init method, you bootstrap your presenter (#5). Last, you create a set property (#6) for the data provider where you create an event to notify the presenter that the data provider was updated. Listing 4 shows the rest of your pie chart component.

Listing 4 PieChart.mxml (continued)
[code lang=”xml”] <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
xmlns:degrafa="http://www.degrafa.com/2007"
creationComplete="init()">
…
</fx:Script>
<mx:Spacer width="10"/> #1
<degrafa:Surface id="pieSurface"
width="200" height="200"> #2
<degrafa:GeometryGroup id="pieGroup"> #3
<degrafa:filters>
<mx:DropShadowFilter color="0x000000"
alpha="0.5"/>
</degrafa:filters> #4
</degrafa:GeometryGroup>
</degrafa:Surface>
<mx:DataGrid id="legendDataGrid"> #5
<mx:columns>
<mx:DataGridColumn width="40"
sortable="false" #6
itemRenderer="org.foj.components.PieLegendRenderer"/>
<mx:DataGridColumn dataField="label"
headerText="Label"/>
<mx:DataGridColumn dataField="units"
headerText="Units"/>
</mx:columns>
</mx:DataGrid>
</s:Group>
#1 Spacer to help lay out the component
#2 Degrafa surface
#3 Geometry group containing pie chart
#4 Drop shadow for pie chart
#5 Legend for pie chart
#6 Custom ItemRenderer[/code]
First, you added a spacer (#1) to the component to put a bit of padding between your pie chart and its surrounding components. Next you added a Degrafa Surface component (#2) and a GeometryGroup (#3) to hold the rest of the Degrafa components necessary for the pie chart component. The GeometryGroup is the component to which you’ll add your pie chart slices when you create them. You’ve also added a Drop-ShadowFilter (#4) to the GeometryGroup to add a bit of visual flair to the pie chart. Last you defined the DataGrid component (#5) for your chart legend, with a custom Item-Renderer (#6) to display the color that corresponds to the data in the chart, which you’ll create in a bit.

PieChartSlice

Now that we’ve defined the pie chart component, let’s move on to defining the slices that will make up the pie chart. The pie chart slice is a rather simple component. We probably could have created the pie chart slice programmatically in ActionScript; however, this approach allows us to define sensible defaults declaratively in MXML, adding behavior as well.

Listing 5 PieChartSlice.mxml
[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<degrafa:GeometryGroup xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:degrafa="http://www.degrafa.com/2007"
height="400"
width="400"> #1
<fx:Script>
<![CDATA[
public function refresh():void #2
{
this.graphics.clear();
this.arc.preDraw();
this.arc.draw(graphics, null);
}
]]>
</fx:Script>
<degrafa:EllipticalArc #3
id="arc"
width="200"
height="200"
closureType="pie"/>
</degrafa:GeometryGroup>
Extends GeometryGroup
Your pie chart slice
Adds EllipticalArc[/code]
The pie chart slice will extend from GeometryGroup (#1). Next, you define a refresh method (#2) to abstract behavior away from your presenter. Last you add an EllipticalArc component to the component (#3) and set default values such as its width, height, and most importantly closureType property, which you set to “pie”.

Custom ItemRenderer

The next component you’re going to create is the custom ItemRenderer for the pie chart legend. This simple component will draw a colored box in the data grid cell to correspond with the colors of the pie chart.

Listing 6 PieLegendRenderer.mxml
[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
xmlns:degrafa="http://www.degrafa.com/2007"> #1
<mx:Spacer width="2"/> #2
<degrafa:Surface>
<degrafa:GeometryGroup>
<degrafa:fill> #3
<degrafa:SolidFill id="fill">
<degrafa:color>{data.legend}"</degrafa:color> #4
</degrafa:SolidFill>
</degrafa:fill>
<degrafa:RegularRectangle #5
width="20"
height="20"
fill="{fill}"/>
</degrafa:GeometryGroup>
</degrafa:Surface>
</mx:HBox>
#1 Extends HBox Spacer to help align box
#2 SolidFill for rectangle
#3 Color of legend item
#4 Rectangle[/code]
The ItemRenderer is extending HBox (#1) because all ItemRenderer objects for the DataGrid component must be halo components. Add a Spacer component (#2) to help align the rectangle the way you want it. The SolidFill component (#3) defines the fill color for the RegularRectangle (#5). Now that you’ve finished creating all the visual components for the pie chart, let’s move on to creating the Presenter. An implicitly defined variable is available to the ItemRenderer named data, which corresponds to the item in the dataProvider that you’re rendering. Use this implicit variable to set the color of the Fill object (#4), which is contained in the legend property of the object.

Presenter for the PieChart

Now that all the visual components are created for the pie chart, let’s create the Presenter. The Presenter for the pie chart becomes more involved than any of your previous ones, but it shouldn’t be hard to follow.

Listing 7 PieChartPresenter.as
[code lang=”java”] package org.foj.presenter {
import com.degrafa.paint.SolidFill;
import org.foj.components.PieChart;
import mx.collections.ArrayCollection;
import org.foj.components.PieChartSlice;
import org.foj.event.EventDispatcherFactory;
import org.foj.event.PieChartEvent;
import org.foj.model.PieChartModel;
public class PieChartPresenter {
private var _view:PieChart; #1
private var _model:PieChartModel;
private var _id:String;
private var _dataProvider:ArrayCollection;
public function PieChartPresenter(view:PieChart, id:String) { #2
this._view = view;
this._model = new PieChartModel();
this._id = id;
EventDispatcherFactory.getEventDispatcher()
.addEventListener(PieChartEvent.DATA_PROVIDER_UPDATED,
refreshData);
}
public function set dataProvider(data:ArrayCollection):void { #3
_view.legendDataGrid.dataProvider = data;
this._dataProvider = data;
}
public function get dataProvider():ArrayCollection {
return this._dataProvider;
}
private function refreshData(event:PieChartEvent = null):void { #4
if (event.id == _id) {
changeData(event.data);
}
}
private function changeData(data:ArrayCollection):void {
dataProvider = data;
createSlices();
}
private function createSlices():void { #5
while (dataProvider.length > _view.pieGroup.numChildren) {
_view.pieGroup.addChild(new PieChartSlice());
}
setLegendColors();
redrawSlices();
}
private function setLegendColors():void { #6
for (var i:int = 0; i < dataProvider.length; i++)
{
dataProvider.getItemAt(i).legend = _model.getLegendColorForIndex(i);
}
}
private function redrawSlices():void { #7
var currentAngle:Number = 0;
var totalUnits:Number = _model.getTotalUnits(_dataProvider);
for (var i:int = 0; i < _view.pieGroup.numChildren; i++) {
var slice:PieChartSlice = _view.pieGroup.getChildAt(i)
as PieChartSlice;
var legendColor:Number = _model.getLegendColorForIndex(i);
var arc:Number = i < dataProvider.length ?
_model.getAngleForItem(
dataProvider[i].units, totalUnits) : 0;
// workaround for weird display if only one arc and it’s 360 degrees
arc = arc < 360 ? arc : 359.99; #8
redrawSlice(slice, currentAngle, arc, legendColor);
currentAngle += arc;
}
_view.pieGroup.draw(null, null);
}
private function redrawSlice(slice:PieChartSlice, #9
startAngle:Number,
arc:Number,
color:Number):void {
slice.arc.fill = new SolidFill(color, 1);
slice.arc.startAngle = startAngle;
slice.arc.arc = arc;
slice.refresh();
}
}
}
#1 Private member variables
#2 Constructor
#3 Set property for dataProvider
#4 Event handler
#5 Create slices method
#6 Set legend colors on data
#7 Redraw slices after update
#8 Workaround
#9 Redraw slice[/code]
You first define private member variables to hold onto references to the view and the model, the id of the component this Presenter belongs to, and the dataProvider for your pie chart (#1). The constructor (#2) for this Presenter not only takes in a reference to the view, but also is used to bootstrap the id for the view component because there may be multiple pie charts contained in the application. You also define an event listener for the dataProvider being updated in the view component. Next you define a pair of get and set properties (#3) for the dataProvider you leverage to update the dataProvider property of the legend data grid whenever the data-Provider for the pie chart is updated.

You then define the event handler method for the event that is fired whenever the dataProvider for the view is updated (#4). Inside this method you check to see if the id of the component firing the event is the same as the id that created this Presenter.

That way if there are multiple pie chart components, this method can determine whether or not it needs to react.

The createSlices method (#5) checks to see if the data provider has more elements contained in it than there are pie chart slices in your pie chart. If there are more elements in the data provider, it will create more pie chart slices. In the set-LegendColors method (#6) you iterate through the items in the dataProvider and set the legend property of the item to the corresponding color, which you’ll get from the pie chart model class.

After all of that, refresh your pie chart with a call to the redrawSlices method (#7).

This will iterate over the pie chart slices and update the data values, such as the start angle of the slice and its arc. You iterate over the pie chart slices instead of the data provider because there may be more slices than items in the dataProvider, and this will draw the extra slices with an arc of 0. There is also a little workaround (#8) for when there is only a single slice and its arc is 360, which sets its arc to 359.99 so that it would draw correctly.

After all of the data for the slice is updated, it is passed into the redrawSlice method (#9) to tell the slice to redraw itself.

Model for the PieChart

Now you only have one piece of the MVP triad to complete for your pie chart. Even though the pie chart doesn’t need to call out to any remote services, you’ve still refactored a couple of methods that could be considered business logic rather than presentation logic and have no need to maintain any kind of state. The following listing shows the code for the pie chart model.

Listing 8 PieChartModel.as
[code lang=”java”] package org.foj.model {
import mx.collections.ICollectionView;
public class PieChartModel {
private var colors:Array = [ #1
0x468966,
0xFFB03B,
0xFFF0A5,
0x999574,
0x007D9F,
0x8E2800,
0x8E28F4,
0x0528F4,
0xF42105,
0x0CF405
];
public function getLegendColorForIndex(index:Number):Number { #2
return colors[index];
}
public function getAngleForItem(units:Number,
totalUnits:Number):Number { #3
return ((((units / totalUnits) * 100) * 360) / 100) ;
}
public function getTotalUnits(dataProvider:ICollectionView):Number { #4
var total:Number = 0;
for each(var item:Object in dataProvider) {
total += item.units;
}
return total;
}
}
}
#1 Array of colors for legend
#2 Convenience method for getting color
#3 Calculate angle for item
#4 Calculate total number of items for pie chart[/code]
An array of 10 different hex values (#1) corresponds to the colors you want the pie chart to use for its data points. This number could easily be increased should the need arise for more data points in your graphs; for this example this number should suffice.

Next, you define a convenience method (#2) for getting the color value for a specific index. The method getAngleForItem (#3) takes care of the calculation for determining the size of the angle for an item based on the total number of items contained within the pie chart and the number of items passed in. The last method you define (#4) in your model iterates through the data set passed in and returns back the total number of items for the pie chart.

Summary

In this article, we’ve introduced the Degrafa framework and created a custom pie chart component. Using Degrafa gives us the ability to declaratively build our graphing components rather than having to deal with complex calculations.

Filed Under: Adobe Flex Tagged With: Degrafa

BlazeDS Messaging Services using Flex 4.0

April 7, 2011 by Krishna Srinivasan Leave a Comment

What is BlazeDS Message Service?

The BlazeDS Message Service enabled with publish/subscribe mechanism and infrastructure to allow Flex application to publish and subscribe messages to a collection of messaging destinations with providing the building of real time data push and applications with collaboration. The following steps creates a simple Cricket score card application that helps in understanding the BlazeDS Message Service

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

Step 1: Create messaging destination

A messaging destination depicts a topic that tracks the conversation of producer and consumers.

Define destination for this application:

  1. In the Blazeds server application project, update the messaging-config.xml placed in the Flex folder with following entry.

configuring messaging-config.xml

[code lang=”xml”]
<destination id="cricket">
<properties>
<server>
<message-time-to-live>0</message-time-to-live>
<durable>true</durable>
</server>
</properties>
</destination>
[/code]

And restart Tomcat.

The destination is used to communicate the messaged thru the channel between the client and the server. BlazeDS enables to use either polling channel or streaming for a messaging destination.

What is Polling channel?

A polling channel normally may be configured using a polling interval. As it works in asynchronous mode, it can also wait for data to receive at the server-side. Every poll response concludes the request. Already connected HTTP connections can be used to send sequential poll requests reduce the overhead of polling.

What is streaming channel?

In case of a streaming channel,the server is enabled to send data in incremental basis to the client until the connection is closed. Streaming AMF(Action Message Format) or HTTP channel requires two active browser HTTP connections in order to send the data in both directions.

This articles works with the destination defined by using the default channel defined in the messaging-config.xml file. The client will connect to the message service by using the streaming AMF channel otherwise if there is any issue by using that channel, the client will connect to polling AMF channel.

Step 2: Configure the Flex project

Connect to the BlazeDS server thru the configuration below:

Step 3: Implement the producer for the Cricket Score card update:

[code lang=”xml”]
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="consumer.subscribe()" width="540" height="356">
<fx:Declarations>
<s:Producer id="producer" destination="cricket"/>
<s:Consumer id="consumer" destination="cricket" message="receiveMessage(event)"/>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.messaging.events.MessageEvent;
import mx.messaging.messages.AsyncMessage;
import mx.messaging.messages.IMessage;

private function submitMessage():void
{
var message:IMessage = new AsyncMessage();
message.body = new Date()+": "+msg.text;
producer.send(message);
msg.text = "";
}
private function receiveMessage(event:MessageEvent):void
{
mytext.text += event.message.body.toString()+ "\n";
}
]]>
</fx:Script>
<s:Panel title="Cricket Score Update" chromeColor="#000000" backgroundColor="#FBF8F8" contentBackgroundColor="#FAFBFB" symbolColor="#FBF7F7" rollOverColor="#EFF3F8" borderColor="#FAF5F5" focusColor="#F7F8F9" top="0" left="0" right="0" horizontalCenter="0" verticalCenter="-71" bottom="142" color="#FCF9F9">
<s:TextArea id="mytext" width="100%" height="100%" contentBackgroundColor="#C0E5EE" color="#090808"/>
</s:Panel>
<s:Button label="Send" click="submitMessage()" x="0" y="227"/>
<s:TextInput id="msg" width="100%" enter="submitMessage()" x="80" y="226"/>
</s:Application>

[/code]

Step 4: Create the Consumer for the Cricket Score Update

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="consumer.subscribe()">
<fx:Declarations>
<s:Consumer id="consumer" destination="cricket" message="receiveMessage(event)"/>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.messaging.events.MessageEvent;
private function receiveMessage(event:MessageEvent):void
{
mytext.text += event.message.body.toString()+ "\n";
}
]]>
</fx:Script>
<s:Panel title="Cricket Score Update" width="406" height="188" x="124" y="96" backgroundColor="#FFFFFF" contentBackgroundColor="#991010" chromeColor="#E84242" rollOverColor="#2F69C0">
<s:TextArea editable="false" id="mytext" width="100%" height="100%" contentBackgroundColor="#A1D2D3"/>
</s:Panel>
</s:Application>
[/code]

On the Flex client side, the BlazeDS provides two classes Producer and Consumer from its Message Service API that can be used to publish and subscribe to a destination.
Subscribe() method of the Consumer can be used to subscribe to a destination.

The event of message is triggered on the Consumer object when a message is published to a subscribed destination.

The BlazeDS Message Service can also support and provideJava API to allow a server side component to publish or subscribe messages to a BlazeDS destination. Java Message Service (JMS) topics can also be mapped to work with Flex clients that publish and subscribe to JMS topics.

Step 5: Run the cricket producer application:

The message is received as after sending

Step 6: The message received by the consumer application is as below:

Conclusion

BlazeDS clients can leverage a message-based framework supported by BlazeDS. The message-based channels encapsulate the connection functionality between the Flex client and the BlazeDS server. These channels are collectively gathered into channel sets for channel discovery and channel reliability.

Filed Under: Adobe Flex Tagged With: Adobe Flex 4.0, BlazeDS

Working with BlazeDS Remote Data Services using Flex 4.0

April 7, 2011 by Krishna Srinivasan Leave a Comment

Working with BlazeDS Remote Data Services using Flex 4.0

What is BlazeDS?

BlazeDS is a collection of data services that help and simplify building of data driven RIA. They also improve the performance of remote data access operations. BlazeDS supports and enables real time data push and asynchronous collaborative applications. BlazeDS service is deployed on Java EE web/application server.

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

The Flex components like Remote Object, Producer, Consumer, HTTPService and WebService interact with a BlazeDS server.

BlazeDS supports with three varieties of key services:

  • The Remoting Service: This enables Flex application to directly interact and invoke methods of remote Java objects that are deployed in application server.
  • The Message Service: This supports and enables Flex application to interact with publish/subscribe mechanism to publish and subscribe messages to a messaging destination. This enhances the building of application with real time data push and collaboration.
  • The Proxy Service: This enables Flex application to implement secure and reliable using cross domain service requests. Flex applications can access services from different domains.

BlazeDS looks after instantiating and managing the remote objects’ life cycle configured in remoting-config.xml.

Working with Remote Objects using BlazeDS

  • Step 1: BlazeDS environment setupThe BlazeDS server can be downloaded from the Adobe open source. It works with Tomcat to deploy its services.
  • Step 2: Create a Java Web project FlexWebAppUpdate the web.xml with the following:

    configuring web.xml
    [code lang=”xml”] <!– Http Flex Session by binding listener support –>
    <listener>
    <listener-class>flex.messaging.HttpFlexSession</listener-class>
    </listener>

    <!– Servlet : MessageBroker –>
    <servlet>
    <servlet-name>MessageBrokerServlet</servlet-name>
    <display-name>MessageBrokerServlet</display-name>
    <servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
    <!– loading the services-config.xml –>
    <init-param>
    <param-name>services.configuration.file</param-name>
    <param-value>/WEB-INF/flex/services-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>MessageBrokerServlet</servlet-name>
    <url-pattern>/messagebroker/*</url-pattern>
    </servlet-mapping>[/code]

  • Step 3: Copy and paste the required jars from BlazeDS turnkey server to WEB-INF/lib folder
  • Step 4: Create a folder called flex and place the xml files like messaging-config, proxy-config, remoting-config and services-config inside downloaded from BlazeDS server.The services-config.xml includes and loads the above mentioned xml files.
  • Step 5: Update the remoting-config.xml with following entry:
    [code lang=”xml”] <!—creating the destination for the StockQuoteService remote Java object
    <destination id="stockQuote">
    <properties>
    <source>mypack.StockQuoteService</source>
    </properties>
    </destination>[/code]
  • Step 6: Create the Flex client application as below:
    [code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
    <!– declaring the remote object in the declaration to connect to BlazeDS destination –>
    <fx:Declarations>
    <s:RemoteObject id="myStock" destination="stockQuote"/>
    </fx:Declarations>
    <s:Panel title="Stock Quotes" width="600" height="240"
    horizontalCenter="0"
    verticalCenter="0" backgroundColor="#7DE4D9" contentBackgroundColor="#BEBB5D" chromeColor="#6CB6B3" rollOverColor="#7792BC">
    <s:layout>
    <s:VerticalLayout/>
    </s:layout>
    <!– connecting the data provider of data grid to the remote onject –>
    <mx:DataGrid width="100%" dataProvider="{myStock.getStocks.lastResult}" />
    <!– invoking the method of the remote object –>
    <s:Button label="Get Stocks" click="myStock.getStocks()"/>
    </s:Panel>
    </s:Application>[/code]

Creating server side Java object

  • Step 7: Create the Java application and deploy to the BlazeDS web application
    [code lang=”java”] package mypack;
    import java.util.HashMap;
    public class StockQuoteService {
    HashMap stocks[]=new HashMap[5];
    public StockQuoteService()
    {
    for(int i=0;i<5;i++){
    stocks[i]=new HashMap();
    stocks[i].put("Stock1",Math.random()*100);
    stocks[i].put("Stock2",Math.random()*100);
    stocks[i].put("Stock3",Math.random()*100);
    }
    }
    public HashMap[] getStocks()
    {
    return stocks;
    }
    }[/code]
    The .class of above Java class must be placed in the classes/mypack folder.
  • Step 8: The J2EE BlazeDS server details need to be configured either when the Flex application is created or update in the Flex server details of flex application as follows:

  • Step 9: Restart tomcat
  • Step 10 : run the flex applicationThe data grid incorporates the receiving result from the remote object and prepares the grid accordingly.

Conclusion

The BlazeDS server consists of a Java EE web application. A Flex client sends a request thru a channel then the request is directed tiwards to an endpoint/post on the BlazeDS server. Then the request is further routed thru a chain of Java objects including the MessageBroker , a service, a destination, and adapter objects. The adapter checks to get the request served locally or remote server.

Filed Under: Adobe Flex Tagged With: Adobe Flex 4.0

Charting with Flex 4.0

April 1, 2011 by Krishna Srinivasan Leave a Comment

Flex 4 Charting

Charting is a mechanism of depicting data using graphical elements known as charts.Flex charts are persuasive with using static charts and as well animated. Flex enables to create interactive and attractive dashboards also.

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

This article describes how to create charts, the customization, use multiple axes, and support user interaction using Flex. Flex Charts can also be programmed to work with drag-and-drop operations and draw selections on a collection of data points.

All the Flex charts extend either the Cartesian or the PolarChart class. Cartesian charting works with on the basis of the Cartesian coordinate system using x and y points to describe data points on vertical & horizontal axes.The PolarChart class is base for pie chart that helps to describe regions within a rounded or radial space.

Charts can be created using MXML components or ActionScript classes.

Components in Chart:

  • Chart: The chart is the structure that connects to various parts.
  • Series: A compilation of associated data points
  • Axes: Two type as Horizontal and vertical axes. Flex’s charts are the two-dimensional Flex charts can have can have multiple axes.
  • Axis renderers: for Rendering lines and labels
  • Elements: Various parts like points, annotations, grid lines etc to be displayed.
  • Labels: Labeling the aces and series

Flex provides various types of charts including Area, Bar, Bubble, Candlestick, Column, HLOC, Line, Pie and Plot.It also provides the corresponding Chart classes and Series component classes for the above list.

Series are collections of associated information used for charts to display. Every chart can have at least one series. Each chart type associates with a corresponding series component. The series data can be statically defined or retrieved from remote objects or web services.

How to create Chart?

Creating a chart involves selecting a chart type and using its analogous series component to design the data points, and supplying at least a horizontal axis.

The following Flex program displays the Area Chart:

Area Chart Example
[code lang=”xml”]<?xml version="1.0"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:s="library://ns.adobe.com/flex/spark"
height="600">
<fx:Script><![CDATA[
import mx.collections.ArrayCollection;
// using ArrayCollection as data provider
[Bindable]
public var companyExpenses:ArrayCollection = new ArrayCollection([
{Quarter:"Q1", Profit:1000, Expenses:1500, Amount:750},
{Quarter:"Q2", Profit:2000, Expenses:200, Amount:200},
{Quarter:"Q3", Profit:1500, Expenses:500, Amount:900},
{Quarter:"Q4", Profit:2500, Expenses:500, Amount:500}
]);
]]></fx:Script>
<s:Panel title="Areal Chart">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<!– adding the Area Chart –>
<mx:AreaChart id="myAreaChart" dataProvider="{companyExpenses}"
showDataTips="true">
<!– defining the horizontal axis –>
<mx:horizontalAxis>
<mx:CategoryAxis
dataProvider="{companyExpenses}"
categoryField="Quarter"/>
</mx:horizontalAxis>
<mx:series>
<!– Defining AreaSeries for Area Chart –>
<mx:AreaSeries
yField="Profit"
displayName="Profit"/>
</mx:series>
</mx:AreaChart>
<!– adding the legend –>
<mx:Legend dataProvider="{myAreaChart}"/>
</s:Panel>
</s:Application>
[/code]
The output shows:

Working with Line Charts

Let us consider the Mobile sales report in XML format as below:
[code lang=”html”]
<mobilesales>
<data interval="Q1" mobile="1" xSales="2.32"
mUnits="2" ySales="1.23"/>
<data interval="Q2" mobile="2" xSales="2.42"
mUnits="3" ySales="1.18"/>
<data interval="Q3" mobile="3" xSales="2.22"
mUnits="4" ySales="1.28"/>
<data interval="Q4" mobile="4" xSales="2.52"
mUnits="1" ySales="2.18"/>
</mobilesales>
[/code]
The line chart can be created as follows:
[code lang=”xml”]
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" >
<fx:Declarations>
<fx:XML id="dataXML" source="salesData.xml"/>
<s:XMLListCollection id="salesData"
source="{dataXML.data}"/>
</fx:Declarations>
<s:Panel title="Mobile Product Sales" width="500" height="250">
<s:layout><s:VerticalLayout/></s:layout>
<mx:Legend dataProvider="{salesChart}"/>
<mx:LineChart id="salesChart"
dataProvider="{salesData}"
height="100%" width="100%">
<mx:horizontalAxis>
<mx:CategoryAxis
categoryField="@interval"/>
</mx:horizontalAxis>
<mx:series>
<mx:LineSeries
yField="@mobile"
displayName="Mobiles"/>
<mx:LineSeries
yField="@mUnits"
displayName="Mobile Units"/>
</mx:series>
</mx:LineChart>
</s:Panel>
</s:Application>
[/code]
The output is shown as below:


The Y axis is called as value axis as it represents the value in the series. It by default starts at 0 value and goes to the largest value identified in the series.

The X axis is called as category axis as it represents the category. It labels by default are spread as with the width of the chart.

Chart Legends & Filters

What is Legend?

The Legend component resides outside of the chart tag. The legend connects with the chart’s id property for its source data. The legend recognizes chart’s child series and extorts the design attributes of each series.
[code lang=”xml”]
<mx:Legend dataProvider="{mobileSalesChart}"/>
[/code]
Applying Area Chart for the same data:

Area Chart Example

[code lang=”xml”]
<mx:AreaChart id="mobileSalesChart"
dataProvider="{salesData}"
height="100%" width="100%">
<mx:horizontalAxis>
<mx:CategoryAxis categoryField="@interval"/>
</mx:horizontalAxis>
<mx:series>
<mx:AreaSeries yField="@mobile"
displayName="Mobiles"
alpha="0.6"/>
<mx:AreaSeries yField="@mUnits"
displayName="Mobile Units"
alpha="0.6"/>
</mx:series>
</mx:AreaChart>
[/code]

The output would show as:

Converting the chart into Bar chart

Let us consider the Mobile sales report in XML format for this chart:

[code lang=”xml”]
<mx:BarChart id="salesChart"
dataProvider="{salesData}"
height="100%" width="100%">
<mx:verticalAxis>
<mx:CategoryAxis categoryField="@interval"/>
</mx:verticalAxis>
<mx:series>
<mx:BarSeries xField="@mobile"
displayName="Mobiles"/>
<mx:BarSeries xField="@mUnits"
displayName="Mobile Units"/>
</mx:series>
</mx:BarChart>
[/code]

The output is as shown below:

How to filter Chart Data?

Flex 4 provides three techniques to filter the chart data.

  • filterData
  • filterDataValues
  • filterFunction

filterData is the most fundamental option and holds the boolean value. If it is set to true then invalid null, invalid values in dataset, NAN, undefined, and out of range values will be removed.The default value is false.

The filterData value will be ignored, If the filterFunction or filter-DataValues properties of Series is set.filterDataValues gives the ability to filter null, undefined , NAN and out of range values from the dataset.If data Series has a filterFunction set, then filter-DataValues property will be ignored.

The filter-Function property is the most powerful way of doing the filtering. A filterFunction defined accepts an Array that relates the Series and returns an Array of items.

What is stacking chart?

Stacking is useful feature for charts when to represent the chart with accumulative visualization of series.

Area chart, Bar chart, Column chart support this stacking feature.

The following example the stacking the bar chart:
[code lang=”xml”]
<mx:BarChart type="stacked" id="salesChart"
dataProvider="{salesData}"
height="100%" width="100%">
<mx:verticalAxis>
<mx:CategoryAxis categoryField="@interval"/>
</mx:verticalAxis>
<mx:series>
<mx:BarSeries xField="@mobile"
displayName="Mobiles"/>
<mx:BarSeries xField="@mUnits"
displayName="Mobile Units"/>
</mx:series>
</mx:BarChart>
[/code]

The output is shown as below:

Types of Charts

What is Bubble Chart?

Bubble charts enable to add a third dimension using the size of a bubble as a way of depicting scale. Flex supports normally two-dimensional charts but using this chart, that feature can be enhanced.

minRadiusis Number property specifies minimum value for a data point with defaults value as 0. Similarly maxRadius is with 50 as default.
xField property is optional and contains the related category value.
yField property contains the category/value field.
radiusField property contains the value for the size of the bubble.

The following code illustrates the Bubble chart:

using Bubble chart
[code lang=”xml”]
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var series1:ArrayCollection = new ArrayCollection( [
{"xVal": 30, "yVal": 10, "rad":Math.random()*100 },
{"xVal": 40, "yVal": 20, "rad":Math.random()*100 } ,
{"xVal": 50, "yVal":30, "rad":Math.random()*100 }]);
[Bindable]
private var series2:ArrayCollection = new ArrayCollection( [
{"xVal": 20, "yVal": 20, "rad":Math.random()*100 },
{"xVal": 30, "yVal": 30, "rad":Math.random()*100 },
{"xVal": 40, "yVal": 40, "rad":Math.random()*100 } ]);
]]>
</fx:Script>
<s:layout>
<s:VerticalLayout/>
</s:layout>
<s:Panel title="The Bubble Chart">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<mx:BubbleChart id="myChart"
showDataTips="true">
<mx:series>
<mx:BubbleSeries
dataProvider="{series1}"
displayName="Series 1"
xField="xVal" yField="yVal"
radiusField="rad"/>
<mx:BubbleSeries
dataProvider="{series2}"
displayName="Series 2"
xField="xVal" yField="yVal"
radiusField="rad"/>
</mx:series>
</mx:BubbleChart>
<mx:Legend dataProvider="{myChart}"/>
</s:Panel>

[/code]
The output would show as:

HLOC and Candlestick charts

What are HLOC and Candlestick charts?

Candlesticks and HLOC charts require four parts in one chart. A vertical line specifies high and low values.
A rectangular box that contains the body represents on top of the line. If the box is unfilled, then the top of the box is the confirming the end value. And the bottom of the box is the starting value. If the box is filled in, the top of the box is the starting value if the box is filled in.

HLOC charts are also similar to the same. But they use left and right sticks to designate the starting and ending values.

A vertical line indicates the high and low values. This line represents the series of values.

A left tick indicates the starting value. A right tick indicates the ending value.

The variation is that candlesticks need all four data points. In spite of the HLOC’s name, the starting value is optional. The four data points are needed to build the Candlestick Series and HLOCSeries.

  • highField property contains the high value
  • lowField property contains the low value
  • openField property contains the open value; optional for HLOCSeries
  • closeField property contains the close value
  • xField property contains the category value for the X axis that is optional.

Creating the Candlestick Chart:

[code lang=”xml”]
<fx:Declarations>
<fx:XML id="stockXML" source="hloc.xml"/>
<s:XMLListCollection id="stockInfo"
source="{stockXML.info}"/>
</fx:Declarations>
<s:Panel title="Mobile Stock Quotes"
width="500" height="250">
<s:layout><s:VerticalLayout/></s:layout>
<mx:CandlestickChart id="stockChart"
dataProvider="{stockInfo}"
height="100%" width="100%">
<mx:horizontalAxis>
<mx:CategoryAxis
categoryField="@sdate"/>
</mx:horizontalAxis>
<mx:series>
<mx:CandlestickSeries
highField="@high" lowField="@low"
openField="@opening" closeField="@closing"/>
</mx:series>
</mx:CandlestickChart>
</s:Panel>

===============================================
Define the XML data as below for Mobile stock values

<stockinfo>
<info sdate="03/11/2011" high="25" low="10" opening="22" closing="23"/>
<info sdate="03/12/2011" high="30" low="17" opening="28" closing="20"/>
<info sdate="03/13/2011" high="40" low="22" opening="35" closing="30"/>
<info sdate="03/14/2011" high="50" low="10" opening="45" closing="32"/>
<info sdate="03/15/2011" high="60" low="40" opening="46" closing="48"/>
</stockinfo>

[/code]

The output is as shown below:

After changing the chart to HlocChart, the output would look like

The output is as shown below:

What is Pie Chart?

This chart is used to partition the data segments. The size of each segment indicates weight and value.

Consider the following mobile profit data:
[code lang=”xml”]
<mobiledata>
<profits>
<info name="Mobile1" profit="387465"/>
<info name="Mobile2" profit="578233"/>
<info name="Mobile3" profit="467957"/>
<info name="Mobile4" profit="510647"/>
</profits>
</mobiledata>
[/code]

The pie chart can be implemented as below:
[code lang=”xml”]
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<fx:XML id="mobileXML" source="mydata.xml"/>
<s:XMLListCollection id="mobileData"
source="{mobileXML.profits.info}"/>
</fx:Declarations>
<mx:Legend dataProvider="{mobileProfitChart}"/>
<mx:PieChart id="mobileProfitChart"
dataProvider="{mobileData}"
height="100%" width="100%">
<mx:series>
<mx:PieSeries field="@profit" nameField="@name"
labelPosition="callout"/>
</mx:series>
</mx:PieChart>
[/code]

Types of Charts

What is Plot chart?

A plot is just like a grid and specifically defines where each data point provides. x and y coordinates will be used to plot sets of data.

Create a plot chart as below:

using Plot chart
[code lang=”xml”]
<fx:Script> <![CDATA[
import mx.collections.*;
[Bindable]
public var mydataSet:ArrayCollection;
public function init():void {
var myarray:Array = [];
for (var i:int=0;i < 10;i++) {
var setValues:Object = {
A:Math.random()*100,
B:Math.random()*100,
C:Math.random()*100,
D:Math.random()*100
};
myarray.push(setValues);
}
dataSet = new ArrayCollection(myarray);
}
]]></fx:Script>

<s:Panel title="Plotting Chart">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<mx:PlotChart id="myChart"
dataProvider="{dataSet}" showDataTips="true">
<mx:series>
<mx:PlotSeries
xField="A"
yField="B"
displayName="Series X"/>
<mx:PlotSeries
xField="C"
yField="D"
displayName="Series Y"/>
</mx:series>
</mx:PlotChart>
<mx:Legend id="l1" dataProvider="{myChart}"/>
</s:Panel>
[/code]
The output of plot chart is:

Customizing charts

How to customize charts?

Flex API enables us to work with various charts and provides support to customize them as well.

What is Series stroke?

A stroke enhances the visualization of the line or the outside of the series. To apply a stroke,Property needs to be identified to use for a specified series.

Changing the previous chart by adding the color

[code lang=”xml”]
<fx:Declarations>
<fx:XML id="mobileXML" source="mydata.xml"/>
<s:XMLListCollection id="mobileData"
source="{mobileXML.profits.info}"/>
<fx:Array id="coloring">
<s:SolidColor color="Yellow" alpha="0.5"/>
<s:SolidColor color="Maroon" alpha="0.5"/>
<s:SolidColor color="Red" alpha="0.5"/>
<s:SolidColor color="Blue" alpha="0.5"/>
</fx:Array>
</fx:Declarations>

<mx:Legend dataProvider="{mobileProfitChart}"/>
<mx:PieChart id="mobileProfitChart"
dataProvider="{mobileData}"
height="100%" width="100%" >
<mx:series>
<mx:PieSeries field="@profit" nameField="@name"
labelPosition="callout" fills="{coloring}"/>
</mx:series>
</mx:PieChart>
[/code]

Conclusion

Charting in Flex is very powerful as it can be used to implement various charts for the requirements and building dashboards.

Charts consists of many parts that include series, axes, labels, sub charts , and elements.

Flex provides support for implementing nine types of charts that are required to address to the common requirements. The stroke and fills features can be used to enhance the charts display for effective customization.

Filed Under: Adobe Flex Tagged With: Adobe Flex 4.0

Flex 4 Components Exposed

March 25, 2011 by Krishna Srinivasan Leave a Comment

This article is based on Flex4 in Action, published on 10-November-2010. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information.

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

Flex 4 Components ExposedThis article is taken from the book Flex 4 in Action. The authors discuss Spark component architecture and explain how to create custom components. The article also features skinning with the SparkSkin Object.

You’ve used components since the start of this book. They range from controls like the simple Button that accept input from the user, to container components like the VBox. Custom components are “home-brewed” so to speak, and are created by extending the same base classes as the default components that are part of the Flex framework.

Now we’ll tell you about the underlying foundation of the Spark component architecture in Flex 4. Most importantly, you will learn key facets of that are specific to the Flex 4 Spark architecture. This will get you on your way toward building your own collection of Spark-based components that take advantage of Spark architecture.

Spark Component Architecture

If you’ve been a Flex developer for a little while now, or you’ve used a different framework for client side interface creation, you may have heard of the conceptual Model-View-Controller (MVC) architecture. The Flex 4 Spark component architecture puts a little spin on the MVC pattern, and adds a fourth part – the skin. This means that every Spark-based component has the following four pieces to it:

  • Model: Properties and business logic are contained here, and are usually written in ActionScript. For the sake of best practice, you really should not be placing visual or behavioral logic along with the model. We will elaborate on that in a moment.
  • View: Contains logic used mostly for the layout and positioning of the component on the stage during runtime. This information can be its own ActionScript class, but it is usually more logical to either: A) abstract the logic into a base class so it can be reused by other components, or B) add it to the component’s
    controller class.
  • Controller: This is responsible for defining the behavior of the component, the states that are contained within it, and provides definitions of the sub-parts that are declared in the Skin class using variable names. This typically comes in the form of ActionScript.
  • Skin: Declares all of the visual elements that make up the component. This is usually an MXML file (largely thanks to FXG), and is tightly coupled with the Controller.

There is currently a lot of debate on what we will explain next, and you will ultimately have to exercise best judgment using a combination of your logical reasoning skills, along with the knowledge that you are gaining in this article.

As you saw a moment ago, there are four pieces that make up the Spark component architecture. Where this gets confusing is that you will often only see two classes for these four parts, one in ActionScript and the other MXML. The ActionScript class typically wraps the model, view, and the controller pieces into a single class, while the MXML is strictly meant to act as the skin for the respective component. According to the Flex 4 documentation:

“The general rule is any code that is used by multiple skins belongs in the component class, and any code that is specific to a particular skin implementation lives in the skin.”

This makes sense in theory, but does not usually provide enough of what we often refer to as separation of concerns. This is why you might notice that the better Flex developers are using three layers for their components:

  1. Component: The controller and the view logic, often written in ActionScript
  2. Presentation Model: Contains the code for the model.
  3. Skin: The MXML skin file

With this method, it is reasonable to suggest that this takes things back to the core concept of the Model-View- Controller again; whereas the Component class is the controller, the presentation model class is the model, and the Skin becomes the view element of the MVC architecture.

Let’s put all this theory into practice by taking a look at some real-life situations.

The many flavors of custom components

Creating a custom component means extending a pre-existing class that either directly or indirectly extends one of the Flex framework classes. Picture three 2010 Ford Mustangs side-by-side. The first is the base Mustang Coupe with the standard V6 engine. The second is the Mustang GT with a 4.6-liter V8, upgraded wheels, and some other upgrades. The third is a Shelby Cobra, sporting 510-horsepower, and premium sound and navigation system among other upgrades. The second and third mustangs both extend the base mustang, so they inherit all of the properties of the first, and then add their own additional amenities.

Similarly, the Cobra extends the GT, so the Cobra inherits the properties of the GT and the standard Mustang, while adding its additional features. But wait! How could the Cobra and the GT inherit the properties of the standard Mustang if the engines are different? The answer is that the GT overrides the engine property of the standard Mustang, and the Cobra overrides the engine of the GT.The relationship between these three automobiles is illustrated in the simple class diagram shown in
Figure 1.

When you extend classes in the Flex framework, you inherit the properties, functions, events, and styles from the class you are extending. This makes code a lot more manageable and is one of the fundamental characteristics of object oriented programming and code reusability. Let’s take a look at two different component types.

Simple vs. Composite

There are two major types of custom components: simple and composite. A simple custom component extends a single, pre-existing component.

The fun doesn’t stop there though. When developing Flex applications, you will find it valuable to group simple components together, keeping your application better organized. You can create components that group disparate components in what’s called a composite component, which is a container that holds any number of additional components inside of it.

MXML vs. ActionScript

When developing custom components, you have the option of creating your component in either MXML or ActionScript. In most cases, either one will do. The main advantage of MXML is that you can usually write the code needed with fewer lines. However, some flexibility is lost in regard to object customization, so advanced custom components are almost always written as ActionScript classes.

Creating your component in MXML is often a popular choice for composite components that are not very advanced in nature. An excellent example of this is a shipping information form. It is useful to have a reusable shipping form component because there are many applications that it can be used for. This means that if the component is created with loose couplingin mind,it can be a highly reusable composite component that can be built using MXML.This approach is the easiest to get started with.

MIGRATION TIP
In Flex 3, MXML composite components were usually based on the Flex Canvas container from the Halo library.
In Flex 4, MXML composite components are created using the MXMLComponent base class or the Group class from the Spark library.

Your second option is to create your component in ActionScript. This technique is more advanced because it requires stronger ActionScript skills.You can override the functions of the component class you’re extending from, and you have fine-grained control.

The advantage of this method is that you have far greater power to turn the coolness factor on your custom component into overdrive.The disadvantage is that if you are building a composite component, you can no longer lay out the controls in Flash Builder’s design view. Advanced developers consider this a small price to pay for the increased flexibility, while others feel that it slows down the development process. Finding the formula that works best for you is just a matter of trial-and-error.

Now that you have learned about the options available, the first custom component you will build is of the simple type.

TIP
When it comes to making custom components, your goal should be to make it simple for other developers to use your component (even if it’s complicated inside). Later, we’ll give you tips on how to achieve this goal.

Creating simple custom components

At the most fundamental level, a viewable component (one which is added to the display list of your application) can be categorized according to the purpose served by the component. This includes: controls, containers, item renderers, effects, and skins.

The first custom component that you will build is an extension of the Flex ComboBox, and is considered a control because it is used to control application behavior by initiating an action or sequence of actions when the value is changed.

Build your own home-grown simple ComboBox

Let’s walk through a simple example. Say your application is geocentric, meaning that pieces of information tend to carry location data. As a result, a few forms require the user to specify an address of some sort. To help your users, you want to provide a drop-down menu of U.S. states, as figure 2 demonstrates.

Wouldn’t it be awesome if any part of your application could display this list by calling a single line of code? OK, that’s a loaded statement, but the example is as simple as this:
Listing 1 CBStates.mxml: ComboBox-based custom component

[code lang=”xml”]
<?xml version="1.0" encoding="utf-8"?>
<mx:ComboBox xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo">
<mx:dataProvider>
<mx:Object stateCode="AK" label="Alaska"/>
<mx:Object stateCode="AL" label="Alabama"/>
<!– the rest of the US states –>
</mx:dataProvider>
</mx:ComboBox>
[/code]

In code listing 1, you are presented with an example of simple custom ComboBox control that shows a listing of U.S. states when clicked, and allows selection of a state to be submitted as a data object. This type of component is highly reusable, since it is often needed when creating an address submission form. Listing 2 demonstrates how the component is instantiated with MXML in a Flex application.

Listing 2 Main application file for CBStates

[code lang=”xml”]
2
3
4
5
6
7

<?xml version="1.0"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
backgroundColor="white" xmlns:local="*">
<local:CBStates/>
</s:Application>
[/code]
If you save the two files to the same directory and then run the application, you should end up with a drop-down combo box that lists all the U.S. states, as shown earlier in Figure 1.

One advantage of extending pre-existing Flex user interface components is that anyone who uses it will know its general properties and behaviors as a result of inheritance. In this case, if they know your simple custom component is based on a ComboBox, then they also know your component supports the same properties, events, styles, and functions as the Flex ComboBox control. Now you will take what you just learned and relate it to the Flex 4 Spark library and architecture.

Simple Spark Components

A visual object on the stage is considered a Spark component when it inherits the Spark component architecture by extending a Spark visual component base class. This includes:

  • SkinnableContainer
  • SkinnableDataContainer
  • Group
  • DataGroup
  • MXMLComponent
  • ItemRenderer
  • SkinnableComponent
  • Any Spark library component (e.g. a Spark List)
  • UIComponent

If you are familiar with Flex 3, you may be wondering about the last item in the list, UIComponent. Technically, all visual components in Flex are subclasses of UIComponent, regardless of the component library that the component comes from.
However, certain facets of a component that extends the base UIComponent class can make it a Spark component. For example, if an ActionScript composite component extends UIComponent as the base class, and then instantiates a Group or SkinnableContainer object to hold a set of display objects, then we would refer to it as a Spark composite component.

Most of the time, custom Spark-based components will extend the SkinnableComponent class, as you will see in the examples that will come later.But first, it’s time for some discussion on skins and how the SparkSkin object fits into the picture.

Migration Tip
Beware! One of the biggest compatibility issues that haunted the Flex 4 beta releases involved placing Spark components inside of a Canvas container. The problem reared its ugly head in some unusual ways, even after it was thought to have been resolved. In one of my own experiences, the problem caused compile errors within Flash Builder beta of type “unknown” and source “unknown”. The source of the problem turned out to be a SkinnableContainer that was instantiated inside of a Canvas. The moral of the story here is: if you find yourself debugging and feeling like you are chasing a ghost, consider checking your application to see if you have any Canvas objects before you start banging your head against the wall. If you do, try switching the Canvas to a Group. If that doesn’t fix the problem, we still suggest leaving the Group in place of the Canvas as we have generally found the Group container to be more reliable and functional than Canvas.

Skinning with the SparkSkin object

The decoupling of display logic is one of the most valuable architectural enhancements in the Spark library.

SparkSkin basics

Imagine you just built an application with a set of five custom components. If your five components each extend one of the classes listed earlier from the Spark library, you can create an unlimited number of skins for each of your five custom Spark-based components and keep them organized in an entirely separate package or library. You can then declare a different default skin for each instance of the same component, or even swap skins on the fly by triggering an event during runtime from a user initiated behavior or sequence. Isn’t that cool? Code listing 3 is an example of a Spark skin component.
Listing 3 Example of a skin for a Spark Button
[code lang=”xml”]
<?xml version="1.0" encoding="utf-8"?>
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" #A
xmlns:mx="library://ns.adobe.com/flex/halo"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:ai="http://ns.adobe.com/ai/2008" #B
xmlns:d="http://ns.adobe.com/fxg/2008/dt" #C
minWidth="21" minHeight="21">
<fx:Metadata>
[HostComponent("spark.components.Button")]
</fx:Metadata>
<s:states>
<s:State name="up"/>
<s:State name="over"/>
<s:State name="down"/>
<s:State name="disabled"/>
</s:states>
<!– FXG exported from Adobe Illustrator. –>
<s:Graphic version="1.0" viewHeight="30"
viewWidth="100" ai:appVersion="14.0.0.367" d:id="mainContainer">
<s:Group x="-0.296875" y="-0.5" d:id="firstGroup"
d:type="layer" d:userLabel="Group One">
<s:Group d:id="secondGroup"> #D
<s:Rect x="0.5" y="0.5" width="100"
height="30" ai:knockout="0">
<s:fill>
<s:LinearGradient x="0.5" y="15.5" scaleX="100" rotation="-0">
<s:GradientEntry color="#ffffff" ratio="0"/>
<s:GradientEntry ratio="1"/>
</s:LinearGradient>
</s:fill>
<s:stroke>
<s:SolidColorStroke color="#0000ff" caps="none"
weight="1" joints="miter" miterLimit="4"/>
</s:stroke>
</s:Rect>
</s:Group>
</s:Group>
</s:Graphic>
<s:Label id="labelElement" horizontalCenter="0" #E
verticalCenter="1" left="10" right="10"
top="15" bottom="2">
</s:Label>
</s:SparkSkin>

#A Skins ALWAYS extend SparkSkin in Flex 4
#B Namespace declaration for Illustrator graphics
#C Namespace declaration for FXG graphics
#D Group object followed by design
#E Label declaration followed by style information
[/code]
When you create Spark components, you will usually create two classes for every component. The component class holds behavioral logic, such as events that are dispatched by the component, the component’s data model, skin parts that are implemented by the skin class, and view states that the skin class supports.

The skin class on the other hand, is responsible for managing visual appearance of the component and visual sub components, including how everything is laid out and sized. It must also define the supported view states, graphics, and the data representation.

Migration Tip
FXG stands for “Flash XML Graphics”, and in essence, does for MXML what CSS did for HTML. However, FXG has quite a bit more power under the hood, so while its relationship to Flash and Flex components can be loosely compared to the relationship between CSS and HTML, it does not make logical sense to compare FXG directly to CSS. Many of the limitations imposed on CSS do not exist with FXG. Although it may seem strange to compare FXG to CSS, FXG theoretically accomplishes the same thing that CSS does: It separates layout structure and behavioral code from design and graphics code. This makes it easier to create components that can be quickly and easily integrated into any application without even having to look at the component’s code base.

Using Metadata to Bind Component Skins

The component and skin classes must both contain certain metadata in order for them to work properly together.

The component class must:

  • Define the skin(s) that correspond to it
  • Identify skin parts with the [SkinPart] metadata tag
  • Identify view states that are supported by the component using the [SkinState] tag

The skin class must:

  • Use the [HostComponent] metadata tag to specify the corresponding component
  • Declare view states and define the appearance of each state
  • Define the way skin parts should appear on the stage

Let’s take a look at the three basic essentials of a skin component in further detail, starting with the SkinState
metadata tag.

Migration Tip:
Note that skin parts must have the same name in both the skin class and the corresponding component class or your application will show compile errors or throw runtime errors.

CUSTOM COMPONENT VIEW STATES

The view states that are supported by a component and its corresponding skin must be defined by placing a [SkinState] tag for every view state. These tags are placed directly above the class declaration, as seen in Listing 4.

Listing 4 View states are defined directly above the class statement.

[code lang=”html”]
package
{
import spark.components.supportClasses.SkinnableComponent;
[SkinState("default")] #A
[SkinState("hover")]
[SkinState("selected")]
[SkinState("disabled")]
public class SkinStateExample extends SkinnableComponent
{
public function SkinStateExample()
{
super();
}
}
}
#A SkinState tags preceed the class declaration
[/code]
You can now control the state of the component by setting the currentState property with the component
declaration in MXML, as seen in Listing 5.
Listing 5 Controlling custom component state
[code lang=”xml”]
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/halo"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:MyComp="myComponents.*">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<s:Label text="Login or Register"
fontSize="14" fontWeight="bold"/>
<MyComp:SkinStateExample currentState="default"/> #A
</s:Application>
#A Use currentState to set the component’s state

[/code]
While states are defined in a component’s implementation class and controlled in the skin, skin parts are defined in the MXML skin and controlled by the implementation class.

DEFINING SKIN PARTS

The importance of the [SkinPart] metadata tag is another critical facet of understanding the relationship between component classes and skin classes in the Spark architecture. As you will see in a moment, this metadata tag is especially useful for creating custom components.

The implementation of the SkinPart metadata is simple. First, define skin parts in the same way as you would declare objects in a standard MXML file. For example, if one of your skin parts was a Spark Button with an id property of myButton, you would define it with the code:
[code lang=”xml”]<s:Button id="myButton" width="100" height="20" x="0" y="0"/>
[/code]
Next, declare the skin parts in the component using the [SkinPart] metadata tag. Make sure that the variable is typed the same as what you just defined in the MXML skin, and that the id of the object in the MXML skin matches the name of the variable in the component. The component code for the myButton skin part that you just saw is illustrated in Listing 6.
Listing 6 The SkinPart tag binds component variables to MXML skin part definitions
[code lang=”java”]
public class CustomComponent extends SkinnableComponent
{
public function CustomComponent()
{
super();
}
[SkinPart(required="true")] #A
public var myButton:Button;
}
#A SkinPart metadata binding on the myButton variable
[/code]
Notice the use of the required property after the SkinPart metadata tag is declared. Make sure you declare this property because required is – pardon the pun – required.

You have now learned two of the three essentials to Spark skinning. The third essential element is tying the component implementation to the skin using the HostComponent metadata.

WARNING
In order for your skin part bindings to work, you must be sure to type the respective variable the same as the
MXML object definition and the variable must be named the same as the id attribute that is set on the respective
MXML object definition.

DECLARING THE HOST

The last of the three basic essentials to using skins with custom Spark components is the declaration of the host component in the skin. To accomplish this, you use the [HostComponent] metadata tag. An excellent example of this was provided in the example skin at the beginning of this article, in Listing 3. The code from listing 3 that is used for the declaration of the host component is provided again in Listing 7.
Listing 7 Use HostComponent metadata to bind a skin to a component class
[code lang=”xml”]
<fx:Metadata>
[HostComponent("spark.components.Button")]
</fx:Metadata>

[/code]

Filed Under: Adobe Flex Tagged With: Adobe Flex 4.0

Accessing Server Side Data using Flex 4.0

March 11, 2011 by Krishna Srinivasan Leave a Comment

Introduction

Flex provides 3 classes to communicate with servers namely HttpService,WebService and RemoteObject HTTPService component of Flex 4 can be used with any kind of server-side technology, including PHP pages, ColdFusion Pages, JavaServer Pages (JSPs), Java servlets. This article aims at discussing the httpservice component with JSP for the following task.

  • To send a request to retrive data from Database
  • To send a request with parameters to insert data into the database.

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

To send a request to retrive data from Database

First let us look at the HttpService tag
[code lang=”java”] <S:HTTPService
id="No default."
method="GET|POST|HEAD|OPTIONS|PUT|TRACE|DELETE"
resultFormat="object|array|xml|e4x|flashvars|text"
url="No default."
fault="No default."
result="No default."
>
[/code]

Explanation

  • id-refers to the name of the HttpService instance.
  • Method-Mentions the way how the request is send to the server.
  • resultFormat-configured to specify the format the way the result is expected
  • URL-The URL to which the request is send
  • Fault-A event handling mechanism which makes a call to the handlercode if there is a exception.
  • result-A event handling mechanism which makes a call to the handlercode when the result is recieved from the server.

Example:

The Example shows a Flex application which invokes a JSP page that retrives data from database. The data is formated by JSP code as XML and sent to the flex application and displayed on a data provider.

Files in the project

  1. FlexJSPdemo.mxml:The Flex application that invokes a JSP page
  2. Itemlist.jsp :The JSP page that retrieves data from database using JPA and formats the result in XML format
  3. Product.java :The Entity class that is mapped to Product Table in the database using JPA.
  4. ProductRetriever.java:The Java class that is contacted by JSP to interact with database using JPA.

FlexJSPDemo.mxml
[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" color="#196F82" fontWeight="bold">
<fx:Style source="CopyofFlex4_demos2.css"/>
<fx:Declarations>
<s:HTTPService id="myserv" url="http://localhost:8080/JSPDEMONET/ItemList.jsp"/>
</fx:Declarations>
<s:Panel x="26" y="97" width="705" height="350" title="Using the HttpService">
<mx:DataGrid dataProvider="{myserv.lastResult.Data.Item}" width="508" height="158" enabled="true" color="#3B8FA1" x="81" y="40"/>
<s:Button label="Fetch Data" click="myserv.send()" x="248" y="235"/>
</s:Panel>[/code]
ItemList.jsp
[code lang=”xml”] <%@page import="a.ProductRetriever,
a.Product,
java.util.*"%>
<?xml version="1.0" encoding="utf-8"?>
<Data>
<%
ProductRetriever srv = new ProductRetriever();
List list = null;
list = srv.getData();
for (int i=0; i<list.size(); i++)
{
Product product = (Product)list.get(i);
%>
<Item itemid='<%= product.getProductId()%>’>
<name><%= product.getProductCode() %></name>
<description><%= product.getDescription() %></description>
</Item>
<%}% > </Data>[/code]
Product.java
[code lang=”java”] /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package a;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
*
* @author RekhaKG_Nair
*/
@Entity
@Table(name = "PRODUCT")
@NamedQueries({@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p"), @NamedQuery(name = "Product.findByProductId", query = "SELECT p FROM Product p WHERE p.productId = :productId"), @NamedQuery(name = "Product.findByProductCode", query = "SELECT p FROM Product p WHERE p.productCode = :productCode"), @NamedQuery(name = "Product.findByDescription", query = "SELECT p FROM Product p WHERE p.description = :description")})
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "PRODUCT_ID")
private Integer productId;
@Column(name = "PRODUCT_CODE")
private String productCode;
@Column(name = "DESCRIPTION")
private String description;

public Product() {
}

public Product(Integer productId) {
this.productId = productId;
}

public Integer getProductId() {
return productId;
}

public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

@Override
public int hashCode() {
int hash = 0;
hash += (productId != null ? productId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning – this method won’t work in the case the id fields are not set
if (!(object instanceof Product)) {
return false;
}
Product other = (Product) object;
if ((this.productId == null && other.productId != null) || (this.productId != null && !this.productId.equals(other.productId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "a.Product[productId=" + productId + "]";
}
}[/code]
ProductRetriever.java
[code lang=”java”] package a;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author RekhaKG_Nair
*/
public class ProductRetriever {
EntityManagerFactory emf;
EntityManager em;
public ProductRetriever()
{
emf = Persistence.createEntityManagerFactory("JSPDEMOPU");
em=emf.createEntityManager();
}
public List getData()
{
Query q=em.createNamedQuery("Product.findAll");
return q.getResultList();
}
}[/code]
Persistence.xml
[code lang=”xml”] <?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="JSPDEMOPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>a.Product</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.jdbc.password" value="rekha"/>
<property name="eclipselink.jdbc.user" value="rekha"/>
<property name="eclipselink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="eclipselink.jdbc.url" value="jdbc:derby://localhost:1527/JPA"/>
</properties>
</persistence-unit>
</persistence>[/code]
Output:

How to insert data to a database using Flex and JSP?

In the last section we have seen how to make a request to the server and retrieve the information. This sesction
we will look at sending some parameters as well with our request.We will modify our previous application by

  • creating a new mxml file(SendtoJSPDemo.mxml) to capture input from the user and send it to the server.
  • Modify the ProductRetriver.Java class to perform the insertion operation.
  • Creating a Upload.jsp which gets the request from our Flex code.

SendtoJSPDemo.mxml.

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" color="#196F82" fontWeight="bold">
<fx:Style source="CopyofFlex4_demos2.css"/>
<fx:Declarations>
<s:HTTPService id="myservsd" url="http://hydhtc130252d:8080/JSPDEMONET/upload.jsp" resultFormat="text" fault="faulthand(event)"
result="callme(event)" >
<s:request xmlns="">
<PID>
{PID.text}
</PID>
<Name>
{Name.text}
</Name>
<Disc>
{Disc.text}
</Disc>
</s:request>
</s:HTTPService>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
function callme(event:ResultEvent)
{

var k:String=event.result.toString();
msg.text=k.substr(42,k.length);
}
function faulthand(faulte:FaultEvent)
{
mx.controls.Alert.show(faulte.fault.faultString);
}
]]>
</fx:Script>

<s:Panel x="20" y="110" width="726" height="350" chromeColor="#D5CECE">
<s:TextInput x="141" y="88" id="PID" width="150"/>
<s:TextInput x="141" y="158" id="Name"/>
<s:TextInput x="141" y="219" id="Disc" width="154"/>
<s:Button x="120" y="268" label="ok" click="myservsd.send()"/>
<s:Label x="14" y="98" text="Productid :" width="95" color="#101212"/>
<s:Label x="9" y="158" text="Product Code:" width="124" color="#0B0C0C"/>
<s:Label x="10" y="219" text="Description :" color="#101212"/>
<s:Label x="62" y="25" text="Item Detail Form" width="159" color="#090B0B"/>
<s:Label x="466" y="66" text="Message:" width="149" color="#0C0D0D"/>
<s:RichText x="470" id="msg" y="99" text="Wait….." width="208" height="157" color="#9B2929"/>
</s:Panel>
<s:Label x="184" y="68" text="HttpService" width="329" fontSize="35" color="#111111"/>
</s:Application>[/code]

Explanation:

    • Look at the HTTPService instance that was created ,there is the request tag which configures the data that can be posted.

[code lang=”xml”] <s:request xmlns="">
<PID>
{PID.text}
</PID>
<Name>
{Name.text}
</Name>
<Disc>
{Disc.text}
</Disc>
</s:request>[/code]
Here the code shows that we are sending the parameters PID,Name,Disc so formating as XML.

    • The Event handler code when a result or fault event is generated by HttpService
      The highlighted code below shows the string returned by our JSP code.

[code lang=”java”] function callme(event:ResultEvent)
{
var k:String=event.result.toString();
msg.text=k.substr(42,k.length);
}
function faulthand(faulte:FaultEvent)
{
mx.controls.Alert.show(faulte.fault.faultString);
}[/code]

ProductRetriver.Java

Let us Modify the ProductRetriver.Java to add the Java code to insert data to the database using JPA and sends a boolean value true if insertion was successful otherwise sends false.
[code lang=”java”] public boolean insertProduct(Product p)
{
boolean b =true;
try
{
em.getTransaction().begin();
em.persist(p);
em.getTransaction().commit();
}
catch(Exception e)
{
em.getTransaction().rollback();
b=false;
}
if(b)
return true;
else
return false;
}[/code]

Upload.jsp.

[code lang=”java”] <%@page import="a.ProductRetriever,
a.Product,
java.util.*"%>
<?xml version="1.0" encoding="utf-8"?>
<%
Product product = new Product();
System.out.println("1"+request.getParameter("PID"));
System.out.println("2"+request.getParameter("Name"));
product.setProductId(Integer.parseInt(request.getParameter("PID")));
product.setProductCode(request.getParameter("Name"));
product.setDescription(request.getParameter("Disc"));
boolean b=new ProductRetriever().insertProduct(product);
if(b)
{
out.print("done saved the data about:["+product.getProductId()+","+product.getProductCode()+","+product.getDescription()+"]");
}
%>[/code]
Output:

Conclusion

Flex can not only connect to java but even other server-based applications like ColdFusion, PHP, ASP.NET.
You can retrieve plain text or XML data using HTTP.

Filed Under: Adobe Flex Tagged With: Adobe Flex 4.0

Invoking SOAP and RESTful Web Services using Flex 4.0

February 28, 2011 by Krishna Srinivasan Leave a Comment

Introduction

Flex 4.0 framework facilitates to interact with various kinds of RPC services. Flex Applications can invoke traditional Web Services or Restful web services that returns XML, JSON etc. MXML’s RPC components provides access to SOAP (Simple Object Access Protocol) based web services and Restful web services using HTTP Services. Flex supports requests and responses of web services which are defined as SOAP messages. SOAP defines a standard for communicating the request and response using XML between the Service provider and consumer. The proxy service for LCDS (LiveCycle Data Services) and BlazeDS intercepts requests to web services located remotely, redirects the requests, and returns the responses to the consumers.

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

Working with Web Services

The RPC components and non visual components can be defined in MXML using <fx:Declarations> tag. The Web service components can be created using MMXL code or Action Script (the Object oriented language for Flex) classes also. Let us define a simple SOAP based web service using Java (JAX-WS) that is displayed in a web server to just say Hello to the received user name.

JAX-WS Web Service
[code lang=”java”] package mypack;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

/**
*
* @author GopiKrishna_Chaganti
*/
// defining the web service
@WebService()
public class FlexWS {

/**
* Web service operation
*/// defining the web method for execution
@WebMethod(operationName = "greet")
public String greet(@WebParam(name = "name") // parameter passed
String name) {
return "Hello "+name+", this is a SOAP Web Service!";// response returned in SOAP
}
} [/code]
SOAP based web services need to define the WSDL file so that the consumers can implement the client stubs.
Let us create Flex 4 MXML code to invoke the web service:
[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<!–Defining the Flex app container –>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:ns1="*">

<fx:Declarations>
<!– declaring the web service using Flex 4 spark component,
wsdl attribute to define the location of WSDL,
useProxy to confirm the usage of proxy –>
<s:WebService id="srv" wsdl="http://localhost:8080/FlexWS/FlexWSService?WSDL" useProxy="false" showBusyCursor="true">
<!–once result is received succefully, this block will be used –>
<s:result>
tt.visible = true;
tt.text= event.result.toString();
Alert.show(event.result.toString());
</s:result>
<!–defining the fault handler –>
<s:fault>
Alert.show(event.fault.faultString);
</s:fault>
</s:WebService>
</fx:Declarations>
<s:VGroup width="100%" height="100%" paddingLeft="15" paddingTop="15">
<s:HGroup gap="10">
<mx:FormItem label="Enter your name : " color="#EEE7E7" focusColor="#70EDEE" borderColor="#C14F4F" chromeColor="#0C0C0C" backgroundColor="#271818" dropShadowVisible="true">
<s:TextInput id="t" color="#0C0D0D"/>
</mx:FormItem>
</s:HGroup>
<s:HGroup width="312" height="62">
<s:TextArea id="tt" width="313" height="59" verticalAlign="middle" textAlign="center"/>
</s:HGroup>
<s:TileGroup width="150" height="21">
<!– calling the appropriate method of web service –>
<s:Button label="SOAP" click="srv.greet(t.text)" x="68" y="10"/>
</s:TileGroup>
</s:VGroup>
</s:Application>[/code]
The execution is as follows: After entering the name and clicking the SOAP button the following output can be observed.

Invoing Restful Web Service

Let us modify the code to invoke the Restful web service. The Java restful web service is defined as follows:

JAX-RS Service
[code lang=”java”] package mypack;

import java.util.Date;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

/**
* REST Web Service
*
* @author GopiKrishna_Chaganti
*/
// defining the JAX-RS resource class
@Path("weather")
public class WeatherResource {
// this method is invoked when the GET method is used to invoke the HTTP url.
@GET
@Produces
public String getHtml(@QueryParam("name") String name) { // Query parameter is defined
return "Hi " + name.toUpperCase() + ", you are using Restful Web Service!";
}[/code]
Let us modify the Flex 4 MXML as well as follows:
Add the following mxml code to the <fx:Declarations> tag.
GET and POST methods can mentioned before accessing the Restful web service using method attribute.
[code lang=”xml”] <s:HTTPService id="userRequest" url="http://localhost:8080/FlexWS/resources/weather"
useProxy="false" method="GET">
<s:request xmlns="">
<name>{t.text}</name>
</s:request>
<s:result>
tt.text=event.result.toString();
</s:result>
</s:HTTPService>[/code]
Now the output can be shown as follows:

Invoing Restful Web Service for JSON response

After entering the text and clicking on Restful button the above output will be observed. Let us further add one more method to Restful web service to generate the JSON response for the weather casting request.

JAX-RS Service with JSON response
[code lang=”java”] @Path("weather")
public class WeatherResource {

@GET
@Produces("text/plain")
public String getHtml(@QueryParam("name") String name) {
return "Hi " + name.toUpperCase() + ", you are using Restful Web Service!";
}

@GET
@Produces({"application/json"})
@Path("{city}")
public Weather getJSon(@PathParam("city") String city) {
System.out.println("Request for " + city + " came!");
Weather w = new Weather();
w.setDate(new Date());
w.setCity(city);
if (city.equals("Hyderabad")) {
w.setClimate("Its Hot today!");
} else if (city.equals("Bangalore")) {
w.setClimate("Its Cool today!");
} else {
w.setClimate("Its Humid today!");
}
return w;
}
}[/code]
The above getJSon receives the path parameter for JAX-RS resource class and generates the JSON weather response for the city requested. To achieve this we can use JAXB class to generate the JSON response. The Weather JAXB pojo is as follows:
[code lang=”java”] package mypack;

import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author GopiKrishna_Chaganti
*/
@XmlRootElement // defining the root element
public class Weather {
Date date;
String city;
// defining the sub elements
@XmlElement
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}

@XmlElement
public String getClimate() {
return climate;
}

public void setClimate(String climate) {
this.climate = climate;
}
String climate;
@XmlElement
public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}
}[/code]
The following Flex 4 MXML and Action script will send the request to the weather casting Restful web service.
[code lang=”java”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="100%" height="100%" >
// defining the Action Script
<fx:Script>
<![CDATA[
import com.adobe.serialization.json.*;
import com.adobe.webapis.*;
import com.adobe.webapis.events.*;

import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;

private function search():void
{
// defining the HTTP Service & adding the path parameter
var service:HTTPService = new HTTPService();
service.url = "http://localhost:8080/FlexWS/resources/weather/"+searchStr.text;

// for setting query parameters if any
//service.request.city = searchStr.text;
// result format is considered as text
service.resultFormat = "text";
// adding the listener to execute when the successful response is received
service.addEventListener(ResultEvent.RESULT, onServerResponse);
// sending the request
service.send();
}
private function onServerResponse(event:ResultEvent):void {
try {
// decoding the event response text to JSON response
var json:Object = JSON.decode(event.result as String);
// extracting the data
date.text=json.date.toString();
city.text=json.city.toString();
climate.text=json.climate.toString();
Alert.show("Displayed"+json.city);
}

// handling if fault is received
catch (error:Error) {
Alert.show("Error on search: " + error.message);
}
}

]]>
</fx:Script>

<mx:TextInput id="searchStr" enter="search()" width="200" x="201" y="76"/>
<mx:Label text="Get Weathercasting: " x="56" y="78"/>
<mx:Button id="btnSearch" click="search()" label="Search" x="441" y="77"/>

<mx:Label text="Date : " x="227" y="154"/>
<mx:Text id="date" x="307" y="154"/>
<mx:Label text="City : " x="227" y="185"/>
<mx:Text id="city" x="307" y="185"/>
<mx:Label text="Climate : " x="227" y="213"/>
<mx:Text id="climate" x="307" y="213"/>

</s:Application>[/code]
The output can observed as below:

Invoing Restful Web Service for XML response

Let us add one more method to the restful web resource to represent the climate variations for yesterday, today and tomorrow days.

JAX-RS Service with XML response
[code lang=”java”] String[] cities = {"cityA", "cityB", "cityC", "cityD", "cityE"};

@GET
@Produces({"application/xml"})
@Path("predict")
public WeatherCast[] getXML() {
System.out.println("PREDICT called!!!!!!!");
WeatherCast[] wc = new WeatherCast[5];
for (int i = 0; i < 5; i++) {
wc[i] = new WeatherCast();
wc[i].setCity(cities[i]);
wc[i].setToday(i*Math.random());
wc[i].setYesterday(i*Math.random()-10);
wc[i].setTomorrow(i*Math.random()+10);
}
return wc;
}

====================================================
JAXB class for WeatherCasting
====================================================
package mypack;

import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author GopiKrishna_Chaganti
*/
@XmlRootElement
public class WeatherCast {
String city;
double yesterday;
double today;

public double getToday() {
return today;
}

public void setToday(double today) {
this.today = today;
}

public double getTomorrow() {
return tomorrow;
}

public void setTomorrow(double tomorrow) {
this.tomorrow = tomorrow;
}

public double getYesterday() {
return yesterday;
}

public void setYesterday(double yesterday) {
this.yesterday = yesterday;
}
double tomorrow;

@XmlElement
public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

@XmlElement
public String getClimate() {
return climate;
}

public void setClimate(String climate) {
this.climate = climate;
}
String climate;
}[/code]
Line chart control can be added to MXML code to receive the XML response as below:
[code lang=”java”] <mx:LineChart id="chart" dataProvider="{weatherData.weatherCast}" width="100%" height="100%">
<mx:series>
<mx:LineSeries xField="today" yField="today" displayName="Today" />
<mx:LineSeries xField="tomorrow" yField="tomorrow" displayName="Tomorrow" />
<mx:LineSeries xField="yesterday" yField="yesterday" displayName="Yesterday" />
</mx:series>
</mx:LineChart>
<mx:Legend dataProvider="{chart}" />[/code]
The output can be shown as follows:

Conclusion

Flex supports extensively for web services. Using RPC components, Flex applications can connect to the remote services like SOAP and REST based web services. Flex can also handle various responses like XML, JSON etc using its rich API.

Filed Under: Adobe Flex Tagged With: Adobe Flex 4.0, REST, WebServices

New Features in Flex 4.0

January 18, 2011 by Krishna Srinivasan Leave a Comment

Introduction

This article explains the new features introduced in the latest version Flex 4.0. Initial version of Adobe Flex has been released in 2004. In 2008 Adobe has released the version Flex 3.0. But, the latest version of Flex has many improvements compare to its previous releases. If you are not familiar with developing applications using the Flex framework, please read our previous article on Creating RIA with Adobe Flex framework. That article explains more about the setting up the flex environment and writing the simple hello world example. It is recommended to read before jumping into this article.

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

In this article, we will go through the following new features in detail:

  • Spark component architecture
  • Component layout
  • Themes
  • Skinning
  • FXG

Spark component architecture

Flex 4 has introduced new skinning and component architecture called Spark. Most of the components from the previous version has been reimplemented using this architecture. In the previous version Flex 3.0, the underlying component architecture was Halo. In the Flex 4, it has been replaced by Spark. The main intention of creating Spark is to seperate the Themes, Skin, etc from its core logic.Spark component set includes a drastically redesigned component skinning architecture that combines the ease of MXML-based programming with the power of Flash Player’s visual rendering capabilities.
The following are few important points about the spark component:

  • Spark component architecture is based on existing Flex classes, such as mx.core.UIComponent and mx.effects.Effect.
    So we can have an application developed with the old components with the new architecture.
  • Separate the appearance and the functional logic of the component.
  • A set of components that can be easily customized rather than reimplementing it.for e.g. If the layout of a container
    has to be changed we need to just change the layout property of the container rather than creating a custom container.
  • These components are found in the spark.* package.
  • Some components found in the mx package has not been reimplemeted in the new version. Those components are:

[code] mx.controls.Alert mx.controls.OLAPDataGrid mx.containers.Accordion
mx.controls.AdvancedDataGrid mx.controls.PopUpButton mx.containers.DividedBox
mx.controls.ColorPicker mx.controls.PopUpMenuButton mx.containers.Form
mx.controls.DataGrid mx.controls.ProgressBar mx.containers.Grid
mx.controls.DateChooser mx.controls.RichTextEditor mx.containers.TabNavigator
mx.controls.DateField mx.controls.Tree mx.containers.ViewStack
mx.controls.Menu All chart classes in the mx.charts.* packages
mx.controls.MenuBar All Flex AIR components in the mx.controls package[/code]

Let us look at our first example using the new Spark components

 

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600">
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>
<s:Panel x="103" y="75" width="387" height="200" title="FirstPanel">
<s:Label x="21" y="29" text="My First Program" width="157" height="24"/>
</s:Panel>
</s:Application>[/code]

Notes:

  • fx namespace to reference top-level ActionScript elements, such as Object and Array, and for tags built in to the MXML compiler, such as <fx:Style>
  • The s namespace is used to reference the spark components .s defines the below mentioned namespace library://ns.adobe.com/flex/spark
  • mx namespace is used refers to the mx components.

Component Layout

Layout determines how the child components have to be sized and placed in a Parent Component. In Spark Component architecture the Layout mechanism is decoupled from the individual component. ie.we can set the layout of the component declaratively in MXML or can be modified at runtime. All the predefined layouts can be found in the package Spark.layouts.package.

Some examples of Layouts are

  • BasicLayout
  • HorizontalLayout
  • VerticalLayout
  • TileLayout

Example:Let us look at how we can modify the Layout of a Group to Vertical

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>

<fx:Script>
<![CDATA[
import spark.layouts.HorizontalLayout;
import spark.layouts.VerticalLayout;

var vert:Boolean=false;
function callme()
{

if(vert==true)
{

mygroup.layout=new VerticalLayout();
}
if(vert==false)
{
mygroup.layout=new HorizontalLayout();
}

}

]]>
</fx:Script>

<s:Group x="10" y="20" width="200" height="200" id="mygroup">

<s:Label x="10" y="10" text="A group whose Layout is changed to Vertical or Horizontal on clicking the Buttons"/>
<s:Button x="10" y="50" label="Vertical" click="vert=true;callme()"/>
<s:Button x="90" y="50" label="Horizontal" click="vert=false;callme()"/>
</s:Group>
</s:Application>[/code]

Output:The initial Screen.The component placed as per the x,y coordinates mentioned.

Output:On Clicking the Button with label Vertical</p>

Output:On Clicking the Button with label Horizontal

Themes

A theme defines the appearance of an application built in Flex.The default theme for all Flex 4 components is called Spark.In the earlier version the default theme was called Halo. In Flex 4, MX components also use the Spark theme by default. In case the older theme has to be used we can do it in 2 ways.

  • need to use the theme compiler option to point to the Halo theme swc file or
  • Set the compatibility-version compiler option to 3.0.
    If you use the Halo theme, the theme is applied to all Halo components in your application.
    The Spark components continue to follow the Spark theme unless specifically not overridden

Skinning

In Flex 4 every Spark Components encapsulates the functional behavior of a Component and associated with those Spark Component is a Skin which controls the Visual element of a component including layout.This gives the developer a greater control of how their components look like.Earlier MX components that used the Halo theme for their skins defined their look and feel mostly through style properties. Spark skin classes are written in MXML When creating skins, there is no need to subclass existing skin classes. Instead, copy the source of an existing skin class and create a new class.

Let us look at an example where we are changing the Skin of a Button.

a)Button1.mxml-The Skin being defined

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" alpha.disabled=".5">

<!– states –>
<s:states>
<s:State name="up" />
<s:State name="over" />
<s:State name="down" />
<s:State name="disabled" />
</s:states>

<!– border and fill –>
<s:Rect id="rect" radiusX="4" radiusY="4" top="0" right="0" bottom="0" left="0">
<s:fill>
<s:SolidColor color="0xff22ff" color.down="0x11ff11"/>
</s:fill>
<s:stroke>
<s:SolidColorStroke color="0x131313" weight="3"/>
</s:stroke>
</s:Rect>

<!– text –>
<s:Label text="Button!" color="0x131313"
textAlign="center" verticalAlign="middle"
horizontalCenter="0" verticalCenter="1"
left="12" right="12" top="6" bottom="6" />

</s:Skin>[/code]

b)Applying the skin

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark">
<s:Group x="115" y="55" width="200" height="115">
<s:Button skinClass="Buttonskin1" x="10" y="10"/>
<s:Button label="A Normal Button" x="10" y="66"/>
</s:Group>
<s:Label x="194" y="23" text="A Skin Demo" width="183" height="24"/>
</s:Application> [/code]

Flash XML Graphics (FXG)

Flex 4 support FXG(Flash XML Graphics) a XML syntax to define vector graphics in applications. It is an interchange format with other Adobe tools. i.e using a graphics tool, such as Adobe PhotoShop,Adobe Illustrator, or Adobe Flash Catalyst, we can design and then export as an FXG document, and then use the FXG document as the property of a skin class for a component.

Conclusion

The article was about some of the new features of Adobe Flex 4.There are plenty more new and exciting features in Flex 4 that helps in building RIA in an easy and simple manner.

Filed Under: Adobe Flex Tagged With: Adobe Flex 4.0

Creating RIA with Adobe Flex framework

November 11, 2010 by Krishna Srinivasan Leave a Comment

Introduction

Adobe Flex provides a platform for developing Rich Internet applications (RIA). Adobe Flex is not one thing but it is a combination of various languages, frameworks and builders like MXML, Action Script, SDK and Flex Builder. For creating Adobe Flex applications, we use the markup language MXML which is similar to XML in syntax. Action Script is the scripting language that provides dynamic capabilities. The Adobe Flex SD includes a rich set of APIs for building complex user applications and finally Flex Builder is an IDE based on Eclipse base platform that provides developmental support for building applications.

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

Download and Install Adobe Flex

The following section describes where to download and how to install Flex environment for building Adobe applications. Trial version of Adobe Flex builder is available for download from Adobe site from here for a period of 60 days. At the time of writing this article, the version of Adobe Flex builder available is version 4. After downloading it, install the product by opening up the file ‘Set-up.exe’. Choose the option ‘Continue to use as a trial’ and then click with proceed to get the product installed. For running Adobe Flex applications, a web browser is required with Adobe Flash player support. For IE browser, the flash player ActiveX control can be downloaded from here. For Mozilla firefox, the Adobe Flash player plugin can be downloaded from here.
Once the installation process is done, launch the IDE to setup the default browser used for running Adobe Flex applications. Go to Window –> Preferences and then expand the ‘General’ tree item and select ‘Web Browser’. From here you can configure the default browser to be used for running Adobe Flex applications.

Writing the first Adobe Flex application

Launch the Adobe Flash builder IDE if it is not already opened. Click File –> New –> Other and then expand the folder ‘Flash Builder’ to select the item ‘Flex Project’ and click ‘Next’ to proceed.

Provide a meaningful project name like ‘Hello’. Make sure that the application type ‘Web (runs in Adobe Flash player)’ is selected and the application server type is selected as ‘None/Other’ in the Server technology group and click next.

Leave the default output folder to ‘bin-debug’ and click finish. By default, a file ‘Hello.mxml’ is created with the following contents.

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>
</s:Application>[/code]
As you can see the file ‘Hello.mxml’ contains the markup language. Edit the file in such a way that this file contains the following contents.

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="500" minHeight="500" pageTitle="Hello World" backgroundColor="#A01A1A"
width="600" height="400">

<s:Button label="Hello world from Adobe Flex"
x="214" y="178" id="helloWorld" enabled="true"
fontFamily="Arial" fontSize="15" color="#000000">
</s:Button>

</s:Application>[/code]
As you can see from the above code snippet, the root tag should be ‘Application’ for any Adobe Flex application. The minimum height and width are configured through the attributes ‘minWidth’ and ‘maxWidth’. The text appearing in the title bar of a web page can be controlled through the attribute ‘pageTitle’. The code also makes use of the attributes ‘backgroundColor’, ‘width’ and ‘height’. We want to display the text ‘hello world’ in this application and we wanted to get the text displayed in a button. For this purpose, we have declared the component ‘Button’ originating from the namespace ‘library://ns.adobe.com/flex/spark’. Note that we have used the attribute label to specify the caption for the button. Positioning of the button is done through the co-ordinates ‘x’ and ‘y’. Later on, in this article, we will show how to make use of various layouts for positioning the controls in a more controlled fashion. We have also used other properties of the ‘Button’ component just to illustrate its usage.
Once this application is written, it has to be compiled with a compiler. Adobe Flex builder comes with a pre-configured Flex compiler for compiling Adobe Flex applications. The name of the compiler for compiling MXML applications is ‘mxmlc.exe’ (read as compiler for mxml). Command-line invocation of this compiler can also be done. Go to the folder ‘ADOBE_FLEX_BUILDER_INSTALL_HOME\ sdks\4.1.0\bin’, note that ‘ADOBE_FLEX_BUILDER_INSTALL_HOME’ represents the home directory where the Adobe Flex builder IDE got installed and the version ‘4.1.0’ may vary in your environment.

[code lang=”xml”] mxmlc PathToMxmlFile[/code]
However, this may not be required at all as the Adobe Flash builder IDE hides the complexities of compiling and running applications though a single click button. Click Ctrl+F11 to launch the application, this will open up the browser (as configured in the Preferences) .

Event Handling

In this section, we will illustrate event handling mechanism in Flex. Events are the corner-stones for any UI oriented applications and it is the mechanism of establishing communication between the user and an application. Events are signaled as a result of some trigger performed by the user such as the click on a button or a hyperlink, entering data in a text field etc. Having said that, there can be cases where events are auto-generated too. For example, it is quite common to fire a validation event when data is being entered in text fields. In Flex, it is the responsibility of components to register themselves to events; the target action to be taken after an event has happened is done through event handlers.
Consider the following login form that illustrates the various types of events and its usage.

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600" width="544" height="200"
applicationComplete="onCreationComplete(event)">

<fx:Script>
<![CDATA[
import mx.controls.Alert;
function loginHandler(event:Event){
Alert.show("Button clicked");
}

function onKeyUp(event:Event){
Alert.show("KeyUp event emitted from " + event.target.toString());
}

function onCreationComplete(event:Event){
Alert.show("Application initialization is completed");
}

]]>
</fx:Script>

<s:Label x="143" y="34" text="Enter your username and password"
width="241" height="25" id="usernamePasswordLabel"
verticalAlign="middle" textAlign="center"
fontFamily="Times New Roman" fontSize="15" fontWeight="bold"/>

<mx:Form x="144" y="62">

<mx:FormItem id="usernameLabel" label="Username:" required="true" x="68" y="32">
<s:TextInput id="userName" x="167" y="33" keyUp="onKeyUp(event)">
</s:TextInput>
</mx:FormItem>

<mx:FormItem id="passwordLabel" label="Password:" required="true" x="68" y="63">
<s:TextInput id="password" displayAsPassword="true" x="167" y="62" keyUp="onKeyUp(event)">
</s:TextInput>
</mx:FormItem>

<mx:FormItem>
<s:Button id = "loginButton" label="Login" x="120" y="108" click="loginHandler(event)">
</s:Button>
</mx:FormItem>

</mx:Form>

</s:Application>[/code]
The above application displays a login form that provides username and password capabilities along with a login button. To indicate that the components username/password belong to a form, the element ‘Form’ is used. The visual controls username, password and button are encapsulated as a combination of ‘FormItem’ and element that is specific to a control. Note that the above declaration dictates the usage of nested controls where for a form, we have a form item, and under a form item there can be text field or a button. Username and passwords must be mandatory, to denote this we have used the attribute ‘required’ for these controls which draws an asterisk (*) after the label names. This doesn’t mean that if someone didn’t enter any value for username/password, the validation will happen, this just provides an indication to the user of the application that the fields are mandatory. For a password field, the value entered by the user shouldn’t be displayed; instead the value should be masked with some pattern. To enable this support, the attribute ‘displayAsPassword’ is used which by default will mask the value entered by the user with ‘*’. Launching the application will bring up the browser similar to the following,

We have written event handlers for three different types of events – after the application initialization is complete, while entering data in the username and the text field components and when the user clicks the login button. Note that event handlers or any other Action script related programming has to be done within the ” block. Note that every event handler is written as a function that should take any implicit parameter of type ‘Event’. Also note how the formal parameter is used in the function declaration – the formal parameter name followed by its type, e.g event:Event. Within the implementation of the function, we have just alerted indicating that that particular event has happened through ‘Alert.show’.
Now that we have actually how event handlers can be written, it’s time to see how components are wired with events. The first event that occurs when the application initialization is complete is registered as part of the ‘Application’ declaration like the following,

[code lang=”xml”]
<s:Application applicationComplete="onCreationComplete(event)">[/code]
Note that the event name ‘applicationComplete’ is registered for the event handler ‘onCreationComplete’. Similarly, handling key events for text-based components is done through ‘keyUp’ events and for handling click buttons (applicable for a Button components), the event name ‘click’ is used.

Validating data

It is quite normal to validate the data entered by the user in any form of application before submitting them. Adobe Flex provides rich validation support; the framework comes up with built-in support for many of the commonly used validators that can validate data available in the form of string, text, date etc. Given below is the list of commonly used validators available in Adobe Flex, note that the list is not exhaustive.

  • String Validator
  • Number Validator
  • Date Validator
  • Phone Number Validator
  • Email Address Validator
  • Currency Validator
  • Credit Card Validator
  • ZipCode Validator

The usage of validator will be illustrated in this section with an example. The example application prompts the user to input various user details like name, age, date of birth, sex, country, state, email id, phone number, credit card number etc.

Have a look at the following code for the above form.

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600" pageTitle="Enter User details"
backgroundColor="#B1A9A9">

<fx:Declarations>
<mx:StringValidator id="nameValidator" source="{username}" property="text"
minLength="4" maxLength="20" requiredFieldError="Name is mandatory."
tooShortError="Name is too short. Enter value which is atleast 4 characters"
tooLongError="Name value is too long. Enter value which is not more than 20 characters"/>

<mx:NumberValidator id="ageValidator" source="{age}" property="text" minValue="1" maxValue="100"
requiredFieldError="Age is mandatory" allowNegative="false"/>

<mx:PhoneNumberValidator id="phoneNoValidator" source="{phoneNumber}" property="text"
invalidCharError="Phone number is invalid" minDigits="8" requiredFieldError="Phone number is mandatory"
wrongLengthError="Error in phone number length"/>

<mx:EmailValidator id="emailValidator" source="{mailId}" property="text"
invalidCharError="Email id contains invalid chars" missingAtSignError="@ sign is missing"
missingPeriodInDomainError="Period sign is missing" missingUsernameError="Username is missing in email id"
requiredFieldError="Email address is mandatory"/>

<mx:CreditCardValidator id="ccValidator" source="{creditCardNo}" property="text"
invalidCharError="CC contains invalid characters" requiredFieldError="CC is mandatory"/>

<mx:ZipCodeValidator id="zipCodeValidator" source="{zipCode}" property="text"
invalidCharError="Zip Code value is invalid" requiredFieldError="Zip Code is mandatory"/>
</fx:Declarations>

<s:Label x="267" y="10" text="Fill in the user details given below
" height="24" width="311"
id="userDetailsLabel" fontWeight="bold"
verticalAlign="middle" textAlign="center" fontSize="18"/>

<mx:Form height="383" x="267" y="57" backgroundColor="#E77070" width="311" id="userDetailsForm" label="User Details">

<mx:FormItem label="Name" required="true" x="68" y="32">
<s:TextInput id="username" x="167" y="33">
</s:TextInput>
</mx:FormItem>

<mx:FormItem label="Age:" required="true" x="68" y="63">
<s:TextInput id="age" x="167" y="62">
</s:TextInput>
</mx:FormItem>

<mx:FormItem label="Sex:" required="true">
<s:RadioButton label="Male" groupName="sex"/>
<s:RadioButton label="Female" groupName="sex" width="81"/>
</mx:FormItem>

<mx:FormItem label="Date of Birth" required="true">
<s:TextInput id="dateOfBirth" x="167" y="62">
</s:TextInput>
</mx:FormItem>

<mx:FormItem label="Phone Number" required="true">
<s:TextInput id="phoneNumber" x="167" y="62">
</s:TextInput>
</mx:FormItem>

<mx:FormItem label="Email Id" required="true">
<s:TextInput id="mailId" x="167" y="62">
</s:TextInput>
</mx:FormItem>

<mx:FormItem label="Credit Card No" required="true">
<s:TextInput id="creditCardNo" x="167" y="62">
</s:TextInput>
</mx:FormItem>

<mx:FormItem label="Salary Per annum" required="true">
<s:TextInput id="salaryPerAnnum" x="167" y="62">
</s:TextInput>
</mx:FormItem>

<mx:FormItem label="Country" required="true">
<s:ComboBox id="country" x="167" y="62">
<s:ArrayList>
<fx:String>India</fx:String>
<fx:String>Australia</fx:String>
<fx:String>Pakistan</fx:String>
</s:ArrayList>
</s:ComboBox>
</mx:FormItem>

<mx:FormItem label="State" required="true">
<s:ComboBox id="state" x="167" y="62">
<s:ArrayList>
<fx:String>Tamil Nadu</fx:String>
<fx:String>Karnataka</fx:String>
</s:ArrayList>
</s:ComboBox>
</mx:FormItem>

<mx:FormItem label="Zip Code" required="true">
<s:TextInput id="zipCode" x="167" y="62">
</s:TextInput>
</mx:FormItem>
</mx:Form>

<s:Button label="Submit Details" id="submitDetails" x="363" y="461"/>

</s:Application>[/code]
The section ” is used for defining the validators. Note that all the pre-built validators arise from the namespace ‘library://ns.adobe.com/flex/mx’ and hence the namespace prefix ‘mx’ (as declared) has to be used.

The general format for defining any validator is given below.

[code lang=”xml”] <mx:TypeOfValidator id="<IdForValidator>" source="{ComponentId}" property="PropertyOfAComponent"/>[/code]
In the above declaration, the type of validator represents the validator’s class type – e.g. StringValidator, NumericValidator etc. The attribute ‘id’ represents the unique identifier for a validator which can be made meaningful w.r.t to the component owning the validator. For example, to validate a ‘name’ field, we can give the value ‘nameValidator’ for the id attribute. The attribute ‘source’ binds the validator instance to be the component that requires validator and the value must be the identifier given for the component. For example, if the name field component is given a component id of ‘nameComponent’, then this value has to be given. A component will have multiple properties and which of the component’s property has to be validator can be given in the ‘property’ attribute, that said, it is very common to specify the property ‘text’ for text-based controls.
Have a look at the following declaration

[code lang=”xml”] <mx:StringValidator id="nameValidator" source="{username}" property="text"
minLength="4" maxLength="20" requiredFieldError="Name is mandatory."
tooShortError="Name is too short. Enter value which is atleast 4 characters"
tooLongError="Name value is too long. Enter value which is not more than 20 characters"/>[/code]
In the above code snippet, we have defined the ‘StringValidator’ to validate on the ‘text’ property for the component ‘username’. The validation will be fired on this component when the component loses focus. Note that we have given the minimum and the maximum length for the field as 4 and 20 which means that if these constraints are violated, then the messages as configured in the properties ‘tooShortError’ and ‘tooLongError’ will be displayed. We have made the ‘username’ field as mandatory by defining the property ‘requiredFieldError’. Likewise, all validators have special properties specific to that validator.

Manipulating XML Data in Flex controls

In this section, we will see how to use XML as a data provider for various Flex controls. Flex provides a flexible API for dealing with various forms of XML data. We will also explore the various data types and the classes available in Flex for supporting XML for storing and retrieving data. Consider the following example,

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>

<fx:Script>
<![CDATA[

private var employees:XML =
<employees>
<employee id = "1">John</employee>
<employee id = "2">David</employee>
<employee id = "3">Steve</employee>
<employee id = "4">Marcus</employee>
</employees>;

private function displayXmlHandler(event:Event): void{

employeesTA.text = employees.toXMLString();
}

private function clearXmlHandler(event:Event): void{

employeesTA.text = "";
}

]]>
</fx:Script>

<s:TextArea id = "employeesTA" x="274" y="159" width="304" height="163"/>

<s:Button x="313" y="101" label="Display XML" click="displayXmlHandler(event)"/>

<s:Button x="472" y="100" label="Clear XML" click="clearXmlHandler(event)"/>

</s:Application>[/code]
Upon running the above example, it will provide an UI similar to the following in the browser.

The point to be noted is that a variable of type ‘XML’ is declared for storing XML data. The UI for this applications contains a text area along with the two buttons. The button ‘Display XML’ when clicked will try to display the xml content into the text area. The button ‘Clear XML’ does the reverse, i.e. it clears the xml data stored on the text area. For supporting the displaying and clearing of XML text onto the textarea, we have added two event handlers when the buttons are clicked.
The above example is fairly simple and straightforward, however the power of xml lies when it can be used as a data provider for complex Flex controls such as Datagrid. Consider the following example,

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>

</fx:Declarations>

<fx:Script>
<![CDATA[
private var playersXmlData:XML =
<players>
<player id="SACHIN_TEN">
<name>
<firstName>Sachin</firstName>
<lastName>Tendulkar</lastName>
</name>
<playingFor>India</playingFor>
<ODI>320</ODI>
<Runs>16000</Runs>
<Rating>1</Rating>
</player>
<player id="BR_LARA">
<name>
<firstName>Brian</firstName>
<lastName>Lara</lastName>
</name>
<playingFor>West Indies</playingFor>
<ODI>200</ODI>
<Runs>9000</Runs>
<Rating>10</Rating>
</player>
<player id="RKY_PONTING">
<name>
<firstName>Ricky</firstName>
<lastName>Ponting</lastName>
</name>
<playingFor>Australia</playingFor>
<ODI>260</ODI>
<Runs>12000</Runs>
<Rating>7</Rating>
</player>
</players>;

private function getName(player:Object, column:DataGridColumn): String {
var xml:XML = XML(player);
return player.name.firstName + " "+ player.name.lastName;
}
]]>
</fx:Script>

<mx:Panel title="Players Information" width="662" height="244" x="116" y="144"
id="playersInfo" backgroundColor="#DB5C5C" contentBackgroundColor="#0B2973"
borderColor="#000000" fontSize="20" fontStyle="normal" fontWeight="bold">
<mx:DataGrid id="playersGrid" dataProvider="{playersXmlData.player}"
height="199" width="100%" variableRowHeight="true" fontSize="20">
<mx:columns>
<mx:DataGridColumn headerText="Id" dataField="@id"
color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
<mx:DataGridColumn headerText="Name" labelFunction="getName"
color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
<mx:DataGridColumn headerText="Country" dataField="playingFor"
color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
<mx:DataGridColumn headerText="Total ODI Matches" dataField="ODI"
color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
<mx:DataGridColumn headerText="Total Runs in ODI" dataField="Runs"
color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
<mx:DataGridColumn headerText="ICC Rating" dataField="Rating"
color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
</mx:columns>
</mx:DataGrid>
</mx:Panel>

</s:Application>[/code]
The scripting block for this application contains the declaration of XML that contains various details of some players. Then after that we draw a panel using ‘mx:Panel’ element for holding the Grid component. We have expressed the title for the Panel through the attribute ‘title’. The data source for the grid component comes from the ‘players xml’ and hence the attribute ‘dataProvider’ is used to specify this. A data grid is expected to contain a series of columns with static information (in the form of heading) and dynamic information. These details are expressed through the elements ‘mx:columns’ and ‘mx:DataGridColumn’. For displaying the static header text we have used the attribute ‘headerText’.
We have used three different ways for extracting information from the XML in this example. The first way is for referring the attributes. For attributes, the attribute name has to be prefixed with ‘@’ symbol. For example, ‘id’ appears to be an attribute and the same has been referred as ‘@id’ in the dataField of the grid component. Referring child elements are straightforward, the child element name can appear directly in the dataField attribute. The final way for fetching information to be displayed is to have a special type of function that operates/aggregates data from the complex xml element. For example, in order to display the name of the player which appears as two child elements ‘firstName’ and ‘lastName’, we have define a function ‘getName()’ which returns the combined value of the child element ‘firstName’ and ‘lastName’. Note the first argument passed to the function is the current player object and the second argument is the column object. Within the implementation of the function, we have returned the player’s complete name by taking the first and the last name into consideration.

Formatting Data

In this section, we will see how to format the data before displaying it. Like Validators, Adobe Flex comes with a set of formatters that suits the basic needs. For example, it provides formatters for formatting numbers, currency, phone number, date etc. Have a look at the following code that makes use of the formatters.

[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">

<fx:Declarations>

<mx:NumberFormatter id="numberFormatter" useNegativeSign="true" precision="3"
error="The format of the number is incorrect">
</mx:NumberFormatter>

<mx:CurrencyFormatter id="currencyFormatter" currencySymbol="Rs " useNegativeSign="true"
error="The format of currency is incorrect">
</mx:CurrencyFormatter>

<mx:DateFormatter id="dateFormatter" error="Date format is incorrect" formatString="MM/DD/YYYY">
</mx:DateFormatter>

<mx:PhoneFormatter id="phoneFormatter" error="Phone format is invalid" formatString="### – #### ####">
</mx:PhoneFormatter>

</fx:Declarations>

<fx:Script>
<![CDATA[

private var textXML:XML =
<Data>
<Number>-10.123243</Number>
<Currency>803432.323</Currency>
<Date>01/01/10 10:33</Date>
<Phone>08041413131</Phone>
</Data>;

]]>
</fx:Script>

<s:Panel x="80" y="148" width="675" height="236" id="formatterId" title="Formatter Test">
<s:Label text="Currency: Original Value -> {textXML.Currency}, Formatted Value -> {currencyFormatter.format(textXML.Currency)}"
x="7" y="24" height="30" fontWeight="bold" width="616"/>
<s:Label text="Number: Original Value -> {textXML.Number}, Formatted Value -> {numberFormatter.format(textXML.Number)}"
x="10" y="62" height="28" width="613" fontWeight="bold"/>
<s:Label text="Date: Original Value -> {textXML.Date}, Formatted Value -> {dateFormatter.format(String(textXML.Date))}"
x="10" y="121" height="28" width="613" fontWeight="bold"/>
<s:Label text="Phone: Original Value -> {textXML.Phone}, Formatted Value -> {phoneFormatter.format(textXML.Phone)}"
x="10" y="157" height="28" width="613" fontWeight="bold"/>
</s:Panel>

</s:Application>[/code]
Like the usage of validators, formatters are declared within the ‘fx:Declarations’ section. We have used ‘NumberFormatter’, ‘CurrencyFormatter’, DateFormatter’ and ‘PhoneFormatter’ for formatting numbers, currency, date and phone numbers respectively. Later on in the ‘fx:Script’ block, we have created some sample data to be formatted which were later referred in the UI components. Note that for performing the formatting operation, we have to call the format() method by passing in the data to be formatted. We have used the label component for displaying the value before formatting and the value that got modified after formatting. Running the above program will result in an output similar to the following.

Conclusion

In this article, we saw an introduction to the basic level of programming in Adobe Flex. The article initially started with explaining how to setup the Adobe Flex environment with the introduction to Adobe Flex Builder and Adobe Flash player plugins. Later on, it showed how to write a simple ‘Hello World’ application. Then the event handler mechanism along with process of validating data were discussed in detail. It was then followed by the usage of XML data along with the complex Grid components with respect to data binding. Finally the article concluded with the usage of Formatters for formatting data.

Filed Under: Adobe Flex Tagged With: Adobe Flex

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved