
150 Use an Event Listener
The final application should look like the following:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" creationComplete="createListener();">
<mx:Script>
<![CDATA[
import flash.events.MouseEvent;
public function createListener():void {
btnConvert.addEventListener(MouseEvent.CLICK,
convertCurrency);
}
public function convertCurrency(e:MouseEvent):void {
var rate:Number = 120;
var price:Number = Number(txtPrice.text);
if (isNaN(price)) {
lblResults.text = "Please enter a valid price.";
} else {
price = price * rate;
lblResults.text = "Price in Yen: " + String(price);
}
}
]]>
</mx:Script>
<mx:Panel x="20" y="20" width="450" height="150" layout="absolute"
title="Currency Converter">
<mx:Label x="25" y="37" text="Price in Dollars"/>
<mx:Label x="120" y="65" id="lblResults"/>
<mx:TextInput x="120" y="35" id="txtPrice"/>
<mx:Button x="290" y="35" label="Convert to Yen" id="btnConvert"/
>
</mx:Panel>
</mx:Application>
6.
Save the file, wait until Flex Builder compiles the application, and click Run in the toolbar.
7. Enter a price and click the Convert to Yen button.
The Label control below the TextInput control displays the price in yen.
In this lesson, you wrote an event listener for a Button control, and then associated it with a
button click event using two different methods. In the first method, you associated it by
specifying it in the
click property in the Button control’s MXML tag. In the second method,
you associated the listener by writing an ActionScript function. To learn more, see Chapter 5,
“Using Events” in Flex 2 Developer’s Guide.
Commentaires sur ces manuels