当我们开发Adob Flex程序时,事件处理是其中最基本也是最重要的一项任务。事件让我们知道在一个Flex程序发生了一些事情。他们可以由用户设备(如鼠标,键盘)产生,或者是外部输入,如一个网络服务调用的返回。当界面或是组件的生命周期发生变化时也变引发事件,例如一个组件的创建或销毁,或是组件的调整。
在我们开始这一节之前,首先要确保我们完成了下面的任务:
创建了Lessons工程
打开自动编译选项
Title: Currency Converter
Width: 450
Height: 150
X: 20
Y: 20
ID: btnConvert
Label: Convert to Yen
清除他的Text属性
将其id属性设置为lblResult
代码清单如下:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<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>
public function convertCurrency():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);
}
}
public function convertCurrency(e:MouseEvent):void {
public function createListener():void {
btnConvert.addEventListener(MouseEvent.CLICK, convertCurrency);
}
<mx:Script>
<![CDATA[
import flash.events.MouseEvent;
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>
creationComplete="createListener();"
<?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>
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>