<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
width="310" height="300" fontSize="12" creationComplete="initApp()" title="用户登录">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function initApp():void
{
this.textCode.text = createCheckCode();
}
private function loginHandle():void
{
var username:String = this.txtUsername.text;
var password:String = this.txtPassword.text;
var inputcode:String = this.txtCode.text;
var code:String = this.textCode.text;
if(username=="")
{
Alert.show("用户名不能为空!");
}
if(password=="")
{
Alert.show("密码不能为空!");
}
if(username == "Admin" && password == "Pass" && inputcode.toLocaleLowerCase() == code.toLocaleLowerCase())
{
currentState="index"; //通过currentState改变状态,即更换界面
}
else
{
if(inputcode.toLocaleLowerCase() != code.toLocaleLowerCase())
{
//使控件获取焦点的写法
application.focusManager.setFocus(txtCode); //该花括号内的该行代码必须放在下一行的前面,否则没有该效果出现
Alert.show("验证码输入错误!");
}
else
{
Alert.show("用户名或密码错误!");
}
}
}
//create validate code
private function createCheckCode():String
{
//初始化
var ran:Number;
var number:Number;
var code:String;
var checkCode:String ="";
//生成四位随机数
for(var i:int=0; i<4; i++)
{
//Math.random生成数为类似为0.1234
ran=Math.random();
number =Math.round(ran*10000);
//如果是2的倍数生成一个数字
if(number % 2 == 0)
//"0"的ASCII码是48
code = String.fromCharCode(48+(number % 10));
//生成一个字母
else
//"A"的ASCII码为65
code = String.fromCharCode(65+(number % 26)) ;
checkCode += code;
}
return checkCode;
}
]]>
</mx:Script>
<!-- about state -->
<mx:states>
<mx:State name="index">
<!-- remove login panel -->
<mx:RemoveChild target="{pnlLogin}"/>
<mx:AddChild position="">
<mx:Label text="Welcome to your new home !" fontSize="13"/>
</mx:AddChild>
</mx:State>
</mx:states>
<mx:Panel width="300" height="280" layout="absolute" id="pnlLogin" fontSize="13" horizontalAlign="center" verticalAlign="middle">
<mx:Label x="18" y="13" text="用户名" id="lblUsername"/>
<mx:Label x="18" y="58" text="密码" id="lblPassword"/>
<mx:Button x="71" y="150" label="登录" id="btnLogin" click="loginHandle()"/>
<mx:TextInput x="71" y="11" id="txtUsername"/>
<mx:TextInput x="71" y="58" id="txtPassword" displayAsPassword="true"/>
<mx:Button x="179" y="150" label="重置" id="btnReset"/>
<mx:Label x="18" y="107" text="校验码" id="lblCode"/>
<mx:TextInput x="71" y="105" id="txtCode" width="52"/>
<mx:LinkButton x="171" y="105" label="看不清?" id="lnkBtnCode" click="initApp()"/>
<mx:Text x="131" y="107" id="textCode"/>
</mx:Panel>
</mx:WindowedApplication>
该示例中包含生成验证码、设置控件的焦点、改变页面的状态(给用户的感觉就是更换页面)。个人认为更换页面的做法上比较麻烦:更换页面的内容需要手写代码;也使页面的代码量变大。不知道有没有其他的写法,搜集中...