How to get the value of a ComboBox in ActionScript - apache-flex

I want to show the value of a ComboBox in it's Change event handler. The labelField is assigned dynamically, so that I don't know what it is when I run the event handler
cmbArea.labelField = qry.outFields[0];
I was hoping that I can have access to the value of selectedItem like:
protected function cmbArea_changeHandler(event:IndexChangeEvent):void{
// TODO Auto-generated method stub
Alert.show(event.target.selectedItem.value);
}
But it didn't work.
Any help would be much appreciated.

It's difficult to debug this without seeing your data provider code or the error message. However, it doesn't matter that the labelField is assigned dynamically. What you have will work if elements in your data provider have a property named "value". If the only property in your data provider is the one you assign as the labelField, you should be able to access it in your change handler with the following:
Alert.show(ComboBox(event.target).selectedItem);

<?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:Script>
<![CDATA[
import mx.controls.Alert;
import spark.events.IndexChangeEvent;
protected function comboBox_changeHandler(event:IndexChangeEvent):void
{
Alert.show(comboBox.selectedItem);
}
]]>
</fx:Script>
<s:ComboBox id="comboBox"
change="comboBox_changeHandler(event)">
<s:dataProvider>
<s:ArrayList>
<fx:String>Item 1</fx:String>
<fx:String>Item 2</fx:String>
<fx:String>Item 3</fx:String>
</s:ArrayList>
</s:dataProvider>
</s:ComboBox>
</s:Application>

I tested the following line and seems it works:
Alert.show(event.target.selectedItem[event.target.labelField]);

Related

Flex datagrid header row right click

I got a Datagrid in my Flex application.
I need to make appear a context menu when the header row is right-clicked.
The latter context menu must not appear when the rest of the datagrid items (the ones containing data) are clicked.
Edit: the application runs in AIR environment, so i got no flash-player troubles
In flex, and more generally in flash, there is no way to catch the the right click event.
I'm not sure about the right mouse click, cos flex apps run in flash player, and right click brings up its menu.
The best bet would be to use headerRelease event on your DatagRid. In your event handler you can then create your menu (maybe in a popup or some hovering panel?) and then do what you need to do there.
Read more about it here
edit:
Maybe you could use a contextMenu class, and attach it to your dataGrid.contextMenu?
Below code may help you: -
I have created sample in which i have added only one ITEM. You can convert it and change logic as per requirement. My idea is to provide one of the base logic. You may gey better solution but this can work for you.
<?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:layout>
<s:VerticalLayout/>
</s:layout>
<mx:DataGrid id="myDG" width="350">
<mx:dataProvider>
<mx:ArrayCollection>
<mx:source>
<fx:Object Artist="" Price="11.99"
Album="Slanted and Enchanted" />
<fx:Object Artist=""
Album="Brighten the Corners" Price="11.99" />
</mx:source>
</mx:ArrayCollection>
</mx:dataProvider>
<mx:columns>
<mx:DataGridColumn dataField="Artist" headerRenderer="StackLabelRenderer"/>
<mx:DataGridColumn dataField="Album" headerRenderer="StackLabelRenderer"/>
<mx:DataGridColumn id="price" dataField="Price" headerRenderer="StackLabelRenderer"/>
</mx:columns>
</mx:DataGrid>
</s:Application>
StackLabelRenderer.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Label xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
click="dispatchClickEvent()">
<fx:Script>
<![CDATA[
import mx.controls.DataGrid;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.controls.dataGridClasses.DataGridListData;
import mx.core.mx_internal;
private function dispatchClickEvent():void
{
trace("Item Clicked")
}
import mx.controls.Alert;
[Bindable]
private var cm:ContextMenu;
override protected function createChildren():void
{
cm = new ContextMenu();
cm.hideBuiltInItems();
cm.addEventListener(ContextMenuEvent.MENU_SELECT, contextMenu_menuSelect);
this.contextMenu = cm;
}
private function contextMenu_menuSelect(evt:ContextMenuEvent):void {
//condition to check length of column data length
var allNull:Boolean=true;
var columnName:String = DataGridColumn(data).headerText;
for each(var o:Object in DataGrid(owner).dataProvider) {
if(o[columnName] != "") {
allNull=false;
break;
}
}
if(!allNull)
{
var cmi:ContextMenuItem = new ContextMenuItem("First Element...", true);
cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, contextMenuItem_menuItemSelect);
cm.customItems = [cmi];
}
}
private function contextMenuItem_menuItemSelect(evt:ContextMenuEvent):void {
}
]]>
</fx:Script>
</mx:Label>

Flex Spark List component item order

I have a regular spark list which is sorted correctly when no item renderer is used. However, when the following item renderer is used, the list shuffles and displays items from previous instances of the list. Any help would be appreciated.
<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
autoDrawBackground="true"
creationComplete="itemRendererInit(event)">
<fx:Script>
<![CDATA[
import flash.utils.setInterval;
import flashx.textLayout.conversion.TextConverter;
import mx.events.FlexEvent;
protected function itemRendererInit(event:FlexEvent):void {
setInterval(resizeItemRenderer, 50);
richtext.textFlow= TextConverter.importToFlow(
'<TextFlow xmlns="http://ns.adobe.com/textLayout/2008"><linkNormalFormat color="#ac0000" textDecoration="none"/><linkHoverFormat color="#ac0000" textDecoration="underline"/><linkActiveFormat color="#ac0000" textDecoration="none"/><p><span fontWeight="bold">' +
data[0].toString() +
':</span><br/><br/>' +
data[1].toString() +
'</p></TextFlow>', TextConverter.TEXT_LAYOUT_FORMAT);
}
private function resizeItemRenderer():void {
richtext.width = parentApplication.width-525;
}
]]>
</fx:Script>
<s:RichEditableText id="richtext"
paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10"
verticalAlign="middle" editable="false" textAlign="left"/>
</s:ItemRenderer>
Just over the top of my head, try overriding commitProperties instead of relying on creationComplete event. On creationComplete, just call invalidateProperties and then call your function from commitProperties().
I eventually found it to be a data binding problem. Thanks #M.D.

Yet another Flex custom events in components question

I can't seem to get one of the most basic uses of events working in Flex 4. I've followed multiple tutorials and looked everywhere. From what I can tell, I'm doing everything right, so there must be some stupid mistake somewhere.
I have a main application file that contains a button. On clicking the button, it fires a custom event which I want my listener in my child component to catch. The event IS firing. The child component event listener is NOT catching that event. No clue why. The custom event is copy-pasted from Adobe's tutorial (minus the custom namespace and comments).
Main Application
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
applicationComplete="init()" xmlns:local="*">
<fx:Metadata>
[Event(name="enableChanged", type="EnableChangeEvent")]
</fx:Metadata>
<fx:Script>
<![CDATA[
import EnableChangeEvent;
import TestComponent;
private function doDispatchEvent(event:MouseEvent):void {
if(dispatchEvent(new EnableChangeEvent(EnableChangeEvent.ENABLE_CHANGED, true)))
{
statusLabel.text = "Event was dispatched";
}
}
public function init():void {
myButton.addEventListener(MouseEvent.CLICK, doDispatchEvent);
}
]]>
</fx:Script>
<s:Button x="95" y="83" label="Button" id="myButton" />
<s:Label x="230" y="83" text="" id="statusLabel" />
<local:TestComponent x="95" y="150" width="300" height="400" />
</s:WindowedApplication>
Child Component (Test)
<?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/mx"
width="100%" height="100%"
initialize="init();">
<fx:Script>
<![CDATA[
import EnableChangeEvent;
private function doFinalAction(event:EnableChangeEvent):void {
myLabel.text = "Custom Event Recieved";
}
private function init():void {
addEventListener(EnableChangeEvent.ENABLE_CHANGED, doFinalAction);
}
]]>
</fx:Script>
<s:Label width="300" height="50" text="Should change on click" id="myLabel" />
</s:Group>
Custom Event (from Adobe)
package {
import flash.events.Event;
public class EnableChangeEvent extends Event
{
public function EnableChangeEvent(type:String, isEnabled:Boolean=false) {
super(type);
this.isEnabled = isEnabled;
}
public static const ENABLE_CHANGED:String = "enableChanged";
public var isEnabled:Boolean;
override public function clone():Event {
return new EnableChangeEvent(type, isEnabled);
}
}
}
Timofei Davydik's answer it correct. Since the Application object dispatches the event, if you want your TestComponent object to catch it, you have to add a listener to a reference of the Application object from within your TestComponent. You can use the TestComponent object's inherited property "parentApplication" to get a reference to the Application object`.
Change the following code in TestComponent.mxml:
private function init():void
{
this.parentApplication.addEventListener(EnableChangeEvent.ENABLE_CHANGED, doFinalAction);
}// end function
[UPDATE]
Personally I feel like your going about using events the wrong way, so I made a similar flex application to demonstrate how to use events in flex.
Main.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:components="components.*"
xmlns:events="events.*"
applicationComplete="init()">
<fx:Script>
<![CDATA[
import events.EnableChangeEvent;
public function init():void
{
label1.text = "Application Complete!";
}// end function
private function onTestButtonEnableChanged(e:EnableChangeEvent):void
{
label2.text = "Enabled = " + e.isEnabled;
}// end function
]]>
</fx:Script>
<s:layout>
<s:VerticalLayout horizontalAlign="center" paddingTop="50" />
</s:layout>
<components:TestButton id="testButton" label="CLICK!" enableChanged="onTestButtonEnableChanged(event)" />
<s:Label id="label1"/>
<s:Label id="label2"/>
</s:WindowedApplication>
TestButton.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Button xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
click="onClick()">
<fx:Metadata>
[Event(name="enableChanged", type="events.EnableChangeEvent")]
</fx:Metadata>
<fx:Script>
<![CDATA[
import events.EnableChangeEvent
private var isEnabled:Boolean;
private function onClick():void
{
isEnabled = !isEnabled;
dispatchEvent(new EnableChangeEvent(EnableChangeEvent.ENABLE_CHANGED, isEnabled));
}// end function
]]>
</fx:Script>
</s:Button>
The main difference between the applications is that the Button object, in this case the TestButton object, dispatches the EnableChangeEvent event when clicked. While dispatching the event we can parse the boolean value for the _isEnabled property of TestButton to the event. Before, the value is inverted using the line isEnabled = !isEnabled. Now we can make use of handling the event using the mxml declaration of the TestButton object with the xml attribute enableChanged.
Also instead of following tutorials you might want to try a book like the one i'm reading. It's called "Adobe Flash Builder 4 and Flex 4 Bible" by David Gassner which you can get as a paperback book or a book for your kindle.
#Taurayi is correct, but to get you current code working with just one change, edit the init of Test Component to look like the following:
private function init():void
{
FlexGlobals.topLevelApplication.addEventListener(EnableChangeEvent.ENABLE_CHANGED, doFinalAction);
}
Your application object dispatches the custom event. Why do you expect your group to "catch" this event? It won't. Custom events have neither capturing nor bubbling phase. So, only listeners added to your application object will listen to this event.

Flash Builder 4: Error #1009 in when Button is wrapped in BorderContainer

This is really bugging me, but I have a component where a Button is wrapped in BorderContainer. I'm passing a custom property to the component at run-time to change the label of the button but Flex is reporting the following error:
Cannot access a property or method of a null object reference
When the error occurs, Flex highlights the following code:
myButton.label = value;
Here's the app:
// MyApp.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:local="*">
<local:MyComp id="myButton" label="My Button"/>
</s:WindowedApplication>
// MyComp.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:BorderContainer 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="400" height="300">
<fx:Script>
<![CDATA[
private var _label:String;
public function get label():String
{
return _label;
}
public function set label(value:String):void
{
_label = value;
myButton.label = value;
}
]]>
</fx:Script>
<s:Button id="myButton" label="Test"/>
</s:BorderContainer>
Any help would be greatly appreciated. Thanks in advance.
The myButton Object is not already created if the setter function for the label property is called the first time. Assign the new label value to myButton.label in commitProperties().
You should read About creating advanced components (most notably "About the component instantiation life cycle") to understand why.

Flex Catch Keydown

I want to handle the keydown event globally in my application and as such have added the event handler to the top most DisplayObject in the display list. However, the event doesn't seem to fire unless the cursor focus is on a Textbox or Datagrid or the like.
How can I have key presses handled globaly by the application?
In response the OP's comment above, here's how to hook it up correctly, namely in the application's creationComplete event:
<?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"
creationComplete="initApp();">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.managers.SystemManager;
public function initApp():void {
systemManager.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown)
}
public function onKeyDown(event:KeyboardEvent):void {
pressedKey.text = event.charCode.toString();
}
]]>
</fx:Script>
<mx:Label x="486" y="63" text="You pressed: "/>
<mx:Label id="pressedKey" x="577" y="58" width="122" text=""/>
</s:Application>
stage.addEventListener(...) ?
First, you won't detect any keystroke until your flex application get the focus.
You can do it automatically by calling a js script at startup that will set the focus on the application
Once done, I would recommand you to add your key listener on systemManager. Doing that will allow you to handle keydown event globally.
ExternalInterface.call('function browserFocus(){document.getElementById(\'APPLICATION_NAME_HERE\').focus();}');
This works only with IE and Opera.

Resources