Posts Tagged ‘flex’

Selectable Text in Flex DataGridColumn

May 24, 2013

Last day my junior asked me a question “How do I make text selectable in a DataGridColumn? I want the user to copy the text from the datagrid.”. Well I had really didn’t thought about that feature till then. Important thing, by default you cannot copy the text shown in the datagrid if you are using the default ItemRenderer. But this turned out to be very very easy one. Couple of options.

1.  The most simple one. Make the ItemRenderer of the datagrid column as mx.controls.Text.

<mx:DataGridColumn dataField="name" headerText="Name" itemRenderer="mx.controls.Text"/>

2. By default the item renderer of a datagrid column is DataGridItemRenderer which is based on TextField. And the selectable property is set to false. So extend another class from DataGridItemRenderer and set the selectable property to true.

package com.renderers
{
    import mx.controls.dataGridClasses.DataGridItemRenderer;

    public class SelectableDataGridItemRenderer extends DataGridItemRenderer
    {
        public function SelectableDataGridItemRenderer()
        {
            super();
            this.selectable = true;
        }
    }
}
<mx:DataGridColumn dataField="name" headerText="Name" itemRenderer="com.renderers.SelectableDataGridItemRenderer"/>

3. Create a custom component with a selectable label and assign it as the ItemRenderer.

SelectableDataGridItemRenderer.mxml

<mx:Label xmlns:mx="http://www.adobe.com/2006/mxml" selectable="true">
</mx:Label>

 

<mx:DataGridColumn dataField="name" headerText="Name" itemRenderer="SelectableDataGridItemRenderer"/>

The last two options are just said, in case the first simple one doesn’t work. If you are using a custom Item Renderer, then you are on your own. 🙂

Happy Coding Guys… 🙂

Send Image to Flex from Java using HTTPService

September 19, 2012

I was doing some technology upgradation myself nowadays. As part of that I was writing my own twitter client, using Servlets as backend and Flex as Frontend. I used Twitter4J for twitter connectivity from Java, and I deployed the application in Jelastic, the rock solid cloud java server. Twitter connectivity, login process, retrieval, posting and retweeting was done and my app was very well working in beta stage. As my next improvement I tried to show up the user profile images. Twitter4J provides you with the profile image url and my task was to read the image and send the image across the network to the flex client. I could easily give the url of the image to the flex image control, but I felt doing like this.

Since I am using servlets, I use HTTPService to get connect to Java. Hence my main task was to send image through XML! What the heck, that was the first question that came to my mind. So I split my task into different steps :

1. Read the image from the URL in Java
2. Convert this into some sort of textual form
3. Send this across to Flex
4. Convert the textual form Image into something so that Flex Image control can render.

Lets go step-by-step.

1.Read the image from the URL in Java

I am 100% sure that there will be different way to read the image than how I did below. But this also do the trick. It just opens the stream of the url Object of type java.net.URL and reads byte chunks and put into a ByteArrayOutputStream.

URL url = "http://somesite.com/someimage.jpg";
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096];
int n;

while ((n = is.read(byteChunk)) > 0 ) {
bais.write(byteChunk, 0, n);
}
}catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
}
finally {
if (is != null) { is.close(); }
}

2. Convert this into some sort of textual form

Our next task is to change this read ByteArrayOutputStream into some textual form so that we can send it through XML. The best and most popular way to do this is to encode it using Base64. There are lots of Base64 encoding and decoding libraries available in the java market, from Oracle, Apache and all. I decided to use the one provided by Oracle themselves. The encoder returns you the binary object in the String format. Hence I wrote an util method for encoding the image from URL and it become like this.


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import sun.misc.BASE64Encoder;

/**
* @author Anoop Nair
*
*/
public class UtilClass {

public static String base64Encode(URL url) throws Exception{
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096];
int n;

while ((n = is.read(byteChunk)) > 0 ) {
bais.write(byteChunk, 0, n);
}
}catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
}
finally {
if (is != null) { is.close(); }
}
BASE64Encoder encoder = new BASE64Encoder();
String encodedImage = encoder.encode(bais.toByteArray());
return encodedImage;
}
}

3. Send this across to Flex

Do I need to say anything about this. Embed this encoded string into an XML and use your HTTPService and its result handler and fault handler to transmit this XML to flex. 🙂 I am becoming lazy here. He He.

4. Render this image in Flex

Thanks to those tons of developers out there who are doing hard-core library development. Bingo, Flex also have a built-in Base64Encoder and Base64Decoder. 🙂  Similar to Java I wrote a Util function in Flex and used the decoder to decode the image and convert it into byte array.


package{

import flash.utils.ByteArray;
import mx.utils.Base64Decoder;

public class UtilClass {
private static var base64Dec:Base64Decoder;

public static function base64Decode(encodedString:String):ByteArray{
var byteArr:ByteArray;

base64Dec = new Base64Decoder();
base64Dec.decode(encodedString);
byteArr = base64Dec.toByteArray();
return byteArr;
}
}
}

This byte array can be loaded and bound into the image control like this, where the ByteArray is stored under the variable userImage :

userImage}"/>

Or this can also be done using actionscript like this :

imgUser.load(userImage)

That’s it guys. It was damn easy, right? But if you wanna be a good developer or programmer, go and read more about Base64 encoding and its algorithm, or try to implement your own encoder. The Apache team is really making us lazy, aren’t they? 😛 That’s it guys, Cheers, Happy Coding 🙂

Set cursor position in the Flex Text Controls

September 19, 2012

You have a text control in flex. At some random event, you need to focus the text control. Simple, right. Just give :

txtInput.setFocus();

All is fine. So what if you need to add some text to the text control? Like the following :

txtInput.text = “@anoop_pk”;
txtInput.setFocus();

This will definitely bring the focus on the control. But hold on. The cursor will be blinking on the beginning of the text and you want it to set to the end of the text. Okay it is quite simple. Flex framework provides with method setSelection for the text controls. Which can be used to select a part of the text in the text controls programatically. The typical usage is like this :

txtInput.setSelection(1,6);

We can use this to achieve our task by giving like this :

txtInput.setSelection(txtInput.text.length, txtInput.text.length);

We are infact selecting nothing, but this will force the cursor to move to the end of the text. Thats it guys, a small tip to keep my writing active. Lots of work. See you. Happy Coding. 🙂

Show a default prompt in Flex Combobox

May 8, 2012

At times, you may need to show a combobox, where none of the items should be selected by default and it should show something like ‘Please Select’. One way is to add this object also to the dataprovider, as the first item. But if you think that is a burden for your dataprovider, then Flex SDK provides you a built in option. To be frank, after working in Flex for more than 4 years, I am finding out this now only. 🙂 You can use the prompt property of the combobox to show a default value. This will go away once you select one option, and you cannot bring it back. (I think so, but there are high chances that this is not true).

eg :

<mx:ComboBox id=”comboBox”  dataProvider=”{dataprovider}”
labelField=”name” prompt=”Please select an entry” />

That’s all guys. Flex Your Life. Cheers. 🙂

Calling Flex / Actionscript functions from Javascript

May 8, 2012

Nowadays I am working with Flex projects, that runs on Lotus Notes platform, which consumes data from Lotus Notes backend. Since there is no remote services like BlazeDS to connect to Notes server, am now greatly dependant on HTTPService and Javascript. Calling a javascript function from Flex is quite easy. Just use the ExternalInterface API. For those who don’t know the way, this is how it is getting called.

In AS3

if(ExternalInterface.available){
ExternalInterface.call(“openNotes”, parameter);
}

In Javascript

function openNotes(notesUrl){
window.open(notesUrl, ”, ‘width=1000,height=600’);
}

It is quite easy. But what if you need to call the reverse. ie, calling actionscript function from javascript. We can use the same ExternalInterface api for achieve this. There is a method called addCallback, available in ExternalInterface. addCallback method registers an ActionScript method as callable from the container. After a successful invocation of addCallBack(), the registered function in the player can be called by JavaScript or ActiveX code in the container. The first parameter is the name by which the container can invoke the function and the second parameter is the function closure to invoke. Below is the step-by-step configuration:

Step 1 : Register the call back from actionscript. For eg, call the below method in the creationComplete or initialize event of the component.

private function createCallBack(event:Event):void{
ExternalInterface.addCallback(“updateNotes”, getNotes);
}

private function getNotes():void{
//do whatever you want after getting the hold
}

Step 2 : Create logic in javascript to invoke the AS3 function.

//Javascript
function updateFlex(){
appName.updateNotes();
}

The appName is the name and id of the embedded swf object in the HTML. Like below :

That’s it. Now you can call the updateFlex javascript method from your HTML and it will invoke the AS3 callback function. Enjoy Coding guys. Flex Your Life. Cheers. 🙂

Flex / AS3 – Remove all children of a container

May 8, 2012

I know this is not that big thing. But still wanna scribble it down. In order to remove all the children of the container, there is no set function available. You can write a generic method, may be a static method and call that. The logic is to iterate over all the available children and remove one by one. Something like this :

static public function removeAllChildren(parent:UIComponent):void{
while(parent.numChildren > 0 ){
parent.removeChildAt( 0 );
}
}

The parent can be either UIComponent or its subclass. The best practice would be to write this method in your component itself, so that this method will become a part of the component. Then you can write something like this :

public function removeAllChildren():void{
while(numChildren > 0 ){
removeChildAt( 0 );
}
}

That’s all guys, Happy Coding. 🙂

Adding Glow Filter to Component

April 26, 2012

I got one requirement where I will draw one custom component and it should glow when we mouse hover it and remove glow when move the mouse out. This is a simple thing, though I am putting this so that you can save time. 🙂

First we need to write a function which will be triggered on both mouse hover and mouse out of the component. Obviously it will accept one MouseEvent. Inside that we need to create one GlowFilter and add this filter to the component. Set the properties for the flow filter such as color, alpha and quality. On mouse out am removing all the filters. This will work for me since I do not have any other filters for the component. If you have other filters, then iterate through the filters and remove only the glow filter. The function will look like below :

private function highLightCircle(event:MouseEvent):void{
            var glowFilter: GlowFilter = new GlowFilter();
            var circ:Object = event.currentTarget;
            if(circ.filters.length == 0){  
                glowFilter.color = 0xFFFFFF;
                glowFilter.alpha = 1;
                glowFilter.blurX = 10;
                glowFilter.blurY = 10;
                glowFilter.quality = BitmapFilterQuality.HIGH;
                circ.filters = [glowFilter];
            }else{
                circ.filters = null;
    }
}

Now we need to call this on mouse over and mouse out. Just add the event listeners to the component object on which you need to apply the filter like below.

circle.addEventListener(MouseEvent.ROLL_OVER, highLightCircle);
circle.addEventListener(MouseEvent.ROLL_OUT, highLightCircle);

Thats all guys. Flex your life. Happy Coding. 🙂

Check if an XML node or attribute exists in E4X format

April 25, 2012

E4X is the heaven when it comes to XML parsing. Since flex natively supports E4X format results, it makes our lives very easy. But there are lots of tips and tricks to play in E4X parsing.

Suppose you have an optional XML node and you need to check whether it exists in the XML. Obviously our actionscript and javascript memories will ask us to try this way if(xml.node != null) or if(xml.node). But if you try this, it is not gonna work. It will probably give you unwanted result or if your day is going too good you will get a reference error. The below are some ways you can try out :

For checking Nodes :

if(xml.someNode.length() > 0){ // Node exists }if(xml.someNode != undefined)
{ // Node exists }

For checking Attributes:

if(xml.@someAttr.length() > 0)
{ // Attribute exists }

if(xml.@someAttr != undefined)
{ // Attribute exists }

That’s it guys. Happy Coding! 🙂 Flex your life.

Datatype serialization from Java to Actionscript

February 24, 2012

Chances are there that we might mistake the datatype, when it gets serialized from Java objects to AS3 objects. The table below shows the java datatype and its corresponding AS3 datatype. This is an excerpt from the live docs.

Java type ActionScript type (AMF 3)
enum (JDK 1.5) String
java.lang.String String
java.lang.Boolean, boolean Boolean
java.lang.Integer, int intIf value < 0xF0000000 || value > 0x0FFFFFFF, the value is promoted to Number due to AMF encoding requirements.
java.lang.Short, short intIf i < 0xF0000000 || i > 0x0FFFFFFF, the value is promoted to Number.
java.lang.Byte, byte[] intIf i < 0xF0000000 || i > 0x0FFFFFFF, the value is promoted to Number.
java.lang.Byte[] flash.utils.ByteArray
java.lang.Double, double Number
java.lang.Long, long Number
java.lang.Float, float Number
java.lang.Character, char String
java.lang.Character[], char[] String
java. math.BigInteger String
java.math.BigDecimal String
java.util.Calendar DateDates are sent in the Coordinated Universal Time (UTC) time zone. Clients and servers must adjust time accordingly for time zones.
java.util.Date DateDates are sent in the UTC time zone. Clients and servers must adjust time accordingly for time zones.
java.util.Collection (for example, java.util.ArrayList) mx.collections.ArrayCollection
java.lang.Object[] Array
java.util.Map Object (untyped). For example, a java.util.Map[] is converted to an Array (of Objects).
java.util.Dictionary Object (untyped)
org.w3c.dom.Document XML object
null null
java.lang.Object (other than previously listed types) Typed ObjectObjects are serialized using Java bean introspection rules and also include public fields. Fields that are static, transient, or nonpublic, as well as bean properties that are nonpublic or static, are excluded.

That’s it guys. Happy Coding. 🙂

Adding Glow to a Shape in AS3

January 12, 2012

Adding a glow to a programatically drawn shape is very easy in actionscript. We just need to create the GlowFilter object and apply it to the filters property. A quick example is follows

var whiteGlow:GlowFilter = new GlowFilter(0xFFFFFF, 0.8, 30, 30, 1, 1, false, false);

var sp:Sprite = new Sprite();
this.addChild(sp);
sp.graphics.drawCircle(100,100,50);
sp.filters = [whiteGlow];

That’s it. Similary you can add other filters such as GradientFilter, BlurFilter, etc. For a detail list of the available display filters refer the livedocs : Available Display Filters.

Happy Coding guys. 🙂


%d bloggers like this: