一个简单的定时器(flex版)
这个定时系统的UML类图如下:
AnalogClockFace类
AnalogClockFace
package com.example.programmingas3.clock
{
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.StaticText;
import flash.events.*;
import flash.text.TextField;
import flash.text.TextFormat;
import mx.core.UIComponent;
/**
* Displays a round clock face with an hour hand, a minute hand, and a second hand.
*/
public class AnalogClockFace extends UIComponent
{
/**
* The desired width of this component, as opposed to the .width
* property which represents tha actual width.
*/
public var w:uint = 200;
/**
* The desired height of this component, as opposed to the .height
* property which represents tha actual height.
*/
public var h:uint = 200;
/**
* The radius from the center of the clock to the
* outer edge of the circular face outline.
*/
public var radius:uint;
/**
* The coordinates of the center of the face.
*/
public var centerX:int;
public var centerY:int;
/**
* The three hands of the clock.
*/
public var hourHand:Shape;
public var minuteHand:Shape;
public var secondHand:Shape;
/**
* The colors of the background and each hand.
* These could be set using parameters or
* styles in the future.
*/
public var bgColor:uint = 0xEEEEFF;
public var hourHandColor:uint = 0x003366;
public var minuteHandColor:uint = 0x000099;
public var secondHandColor:uint = 0xCC0033;
/**
* Stores a snapshot of the current time, so it
* doesn't change while in the middle of drawing the
* three hands.
*/
public var currentTime:Date;
/**
* Contructs a new clock face. The width and
* height will be equal.
*/
public function AnalogClockFace(w:uint)
{
this.w = w;
this.h = w;
// Rounds to the nearest pixel
this.radius = Math.round(this.w / 2);
// The face is always square now, so the
// distance to the center is the same
// horizontally and vertically
this.centerX = this.radius;
this.centerY = this.radius;
}
/**
* Creates the outline, hour labels, and clock hands.
*/
public function init():void
{
// draws the circular clock outline
drawBorder();
// draws the hour numbers
drawLabels();
// creates the three clock hands
createHands();
}
/**
* Draws a circular border.
*/
public function drawBorder():void
{
graphics.lineStyle(0.5, 0x999999);
graphics.beginFill(bgColor);
graphics.drawCircle(centerX, centerY, radius);
graphics.endFill();
}
/**
* Puts numeric labels at the hour points.
*/
public function drawLabels():void
{
for (var i:Number = 1; i <= 12; i++)
{
// Creates a new TextField showing the hour number
var label:TextField = new TextField();
label.text = i.toString();
// Places hour labels around the clock face.
// The sin() and cos() functions both operate on angles in radians.
var angleInRadians:Number = i * 30 * (Math.PI/180)
// Place the label using the sin() and cos() functions to get the x,y coordinates.
// The multiplier value of 0.9 puts the labels inside the outline of the clock face.
// The integer value at the end of the equation adjusts the label position,
// since the x,y coordinate is in the upper left corner.
label.x = centerX + (0.9 * radius * Math.sin( angleInRadians )) - 5;
label.y = centerY - (0.9 * radius * Math.cos( angleInRadians )) - 9;
// Formats the label text.
var tf:TextFormat = new TextFormat();
tf.font = "Arial";
tf.bold = "true";
tf.size = 12;
label.setTextFormat(tf);
// Adds the label to the clock face display list.
addChild(label);
}
}
/**
* Creates hour, minute, and second hands using the 2D drawing API.
*/
public function createHands():void
{
// Uses a Shape since it's the simplest component that supports
// the 2D drawing API.
var hourHandShape:Shape = new Shape();
drawHand(hourHandShape, Math.round(radius * 0.5), hourHandColor, 3.0);
this.hourHand = Shape(addChild(hourHandShape));
this.hourHand.x = centerX;
this.hourHand.y = centerY;
var minuteHandShape:Shape = new Shape();
drawHand(minuteHandShape, Math.round(radius * 0.8), minuteHandColor, 2.0);
this.minuteHand = Shape(addChild(minuteHandShape));
this.minuteHand.x = centerX;
this.minuteHand.y = centerY;
var secondHandShape:Shape = new Shape();
drawHand(secondHandShape, Math.round(radius * 0.9), secondHandColor, 0.5);
this.secondHand = Shape(addChild(secondHandShape));
this.secondHand.x = centerX;
this.secondHand.y = centerY;
}
/**
* Draws a clock hand with a given size, color, and thickness.
*/
public function drawHand(hand:Shape, distance:uint, color:uint, thickness:Number):void
{
hand.graphics.lineStyle(thickness, color);
hand.graphics.moveTo(0, distance);
hand.graphics.lineTo(0, 0);
}
/**
* Called by the parent container when the display is being drawn.
*/
public function draw():void
{
// Stores the current date and time in an instance variable
currentTime = new Date();
showTime(currentTime);
}
/**
* Displays the given Date/Time in that good old analog clock style.
*/
public function showTime(time:Date):void
{
// Gets the time values
var seconds:uint = time.getSeconds();
var minutes:uint = time.getMinutes();
var hours:uint = time.getHours();
// Multiplies by 6 to get degrees
this.secondHand.rotation = 180 + (seconds * 6);
this.minuteHand.rotation = 180 + (minutes * 6);
// Multiplies by 30 to get basic degrees, and then
// adds up to 29.5 degrees (59 * 0.5) to account
// for the minutes
this.hourHand.rotation = 180 + (hours * 30) + (minutes * 0.5);
}
}
}
package com.example.programmingas3.clock
{
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.StaticText;
import flash.events.*;
import flash.text.TextField;
import flash.text.TextFormat;
import mx.core.UIComponent;
/**
* Displays a round clock face with an hour hand, a minute hand, and a second hand.
*/
public class AnalogClockFace extends UIComponent
{
/**
* The desired width of this component, as opposed to the .width
* property which represents tha actual width.
*/
public var w:uint = 200;
/**
* The desired height of this component, as opposed to the .height
* property which represents tha actual height.
*/
public var h:uint = 200;
/**
* The radius from the center of the clock to the
* outer edge of the circular face outline.
*/
public var radius:uint;
/**
* The coordinates of the center of the face.
*/
public var centerX:int;
public var centerY:int;
/**
* The three hands of the clock.
*/
public var hourHand:Shape;
public var minuteHand:Shape;
public var secondHand:Shape;
/**
* The colors of the background and each hand.
* These could be set using parameters or
* styles in the future.
*/
public var bgColor:uint = 0xEEEEFF;
public var hourHandColor:uint = 0x003366;
public var minuteHandColor:uint = 0x000099;
public var secondHandColor:uint = 0xCC0033;
/**
* Stores a snapshot of the current time, so it
* doesn't change while in the middle of drawing the
* three hands.
*/
public var currentTime:Date;
/**
* Contructs a new clock face. The width and
* height will be equal.
*/
public function AnalogClockFace(w:uint)
{
this.w = w;
this.h = w;
// Rounds to the nearest pixel
this.radius = Math.round(this.w / 2);
// The face is always square now, so the
// distance to the center is the same
// horizontally and vertically
this.centerX = this.radius;
this.centerY = this.radius;
}
/**
* Creates the outline, hour labels, and clock hands.
*/
public function init():void
{
// draws the circular clock outline
drawBorder();
// draws the hour numbers
drawLabels();
// creates the three clock hands
createHands();
}
/**
* Draws a circular border.
*/
public function drawBorder():void
{
graphics.lineStyle(0.5, 0x999999);
graphics.beginFill(bgColor);
graphics.drawCircle(centerX, centerY, radius);
graphics.endFill();
}
/**
* Puts numeric labels at the hour points.
*/
public function drawLabels():void
{
for (var i:Number = 1; i <= 12; i++)
{
// Creates a new TextField showing the hour number
var label:TextField = new TextField();
label.text = i.toString();
// Places hour labels around the clock face.
// The sin() and cos() functions both operate on angles in radians.
var angleInRadians:Number = i * 30 * (Math.PI/180)
// Place the label using the sin() and cos() functions to get the x,y coordinates.
// The multiplier value of 0.9 puts the labels inside the outline of the clock face.
// The integer value at the end of the equation adjusts the label position,
// since the x,y coordinate is in the upper left corner.
label.x = centerX + (0.9 * radius * Math.sin( angleInRadians )) - 5;
label.y = centerY - (0.9 * radius * Math.cos( angleInRadians )) - 9;
// Formats the label text.
var tf:TextFormat = new TextFormat();
tf.font = "Arial";
tf.bold = "true";
tf.size = 12;
label.setTextFormat(tf);
// Adds the label to the clock face display list.
addChild(label);
}
}
/**
* Creates hour, minute, and second hands using the 2D drawing API.
*/
public function createHands():void
{
// Uses a Shape since it's the simplest component that supports
// the 2D drawing API.
var hourHandShape:Shape = new Shape();
drawHand(hourHandShape, Math.round(radius * 0.5), hourHandColor, 3.0);
this.hourHand = Shape(addChild(hourHandShape));
this.hourHand.x = centerX;
this.hourHand.y = centerY;
var minuteHandShape:Shape = new Shape();
drawHand(minuteHandShape, Math.round(radius * 0.8), minuteHandColor, 2.0);
this.minuteHand = Shape(addChild(minuteHandShape));
this.minuteHand.x = centerX;
this.minuteHand.y = centerY;
var secondHandShape:Shape = new Shape();
drawHand(secondHandShape, Math.round(radius * 0.9), secondHandColor, 0.5);
this.secondHand = Shape(addChild(secondHandShape));
this.secondHand.x = centerX;
this.secondHand.y = centerY;
}
/**
* Draws a clock hand with a given size, color, and thickness.
*/
public function drawHand(hand:Shape, distance:uint, color:uint, thickness:Number):void
{
hand.graphics.lineStyle(thickness, color);
hand.graphics.moveTo(0, distance);
hand.graphics.lineTo(0, 0);
}
/**
* Called by the parent container when the display is being drawn.
*/
public function draw():void
{
// Stores the current date and time in an instance variable
currentTime = new Date();
showTime(currentTime);
}
/**
* Displays the given Date/Time in that good old analog clock style.
*/
public function showTime(time:Date):void
{
// Gets the time values
var seconds:uint = time.getSeconds();
var minutes:uint = time.getMinutes();
var hours:uint = time.getHours();
// Multiplies by 6 to get degrees
this.secondHand.rotation = 180 + (seconds * 6);
this.minuteHand.rotation = 180 + (minutes * 6);
// Multiplies by 30 to get basic degrees, and then
// adds up to 29.5 degrees (59 * 0.5) to account
// for the minutes
this.hourHand.rotation = 180 + (hours * 30) + (minutes * 0.5);
}
}
}
SimpleClock类
SimpleClock
package com.example.programmingas3.clock
{
import mx.core.UIComponent;
public class SimpleClock extends UIComponent
{
import com.example.programmingas3.clock.AnalogClockFace;
import flash.events.TimerEvent;
import flash.utils.Timer;
/**
* The time display component.
*/
public var face:AnalogClockFace;
/**
* The Timer that acts like a heartbeat for the application.
*/
public var ticker:Timer;
public static const millisecondsPerMinute:int = 1000 * 60;
public static const millisecondsPerHour:int = 1000 * 60 * 60;
public static const millisecondsPerDay:int = 1000 * 60 * 60 * 24;
/**
* Sets up a SimpleClock instance.
*/
public function initClock(faceSize:Number = 200):void
{
// sets the invoice date to today’s date
var invoiceDate:Date = new Date();
// adds 30 days to get the due date
var millisecondsPerDay:int = 1000 * 60 * 60 * 24;
var dueDate:Date = new Date(invoiceDate.getTime() + (30 * millisecondsPerDay));
var oneHourFromNow:Date = new Date(); // starts at the current time
oneHourFromNow.setTime(oneHourFromNow.getTime() + millisecondsPerHour);
// Creates the clock face and adds it to the Display List
face = new AnalogClockFace(Math.max(20, faceSize));
face.init();
addChild(face);
// Draws the initial clock display
face.draw();
// Creates a Timer that fires an event once per second.
ticker = new Timer(1000);
// Designates the onTick() method to handle Timer events
ticker.addEventListener(TimerEvent.TIMER, onTick);
// Starts the clock ticking
ticker.start();
}
/**
* Called once per second when the Timer event is received.
*/
public function onTick(evt:TimerEvent):void
{
// Updates the clock display.
face.draw();
}
}
}
package com.example.programmingas3.clock
{
import mx.core.UIComponent;
public class SimpleClock extends UIComponent
{
import com.example.programmingas3.clock.AnalogClockFace;
import flash.events.TimerEvent;
import flash.utils.Timer;
/**
* The time display component.
*/
public var face:AnalogClockFace;
/**
* The Timer that acts like a heartbeat for the application.
*/
public var ticker:Timer;
public static const millisecondsPerMinute:int = 1000 * 60;
public static const millisecondsPerHour:int = 1000 * 60 * 60;
public static const millisecondsPerDay:int = 1000 * 60 * 60 * 24;
/**
* Sets up a SimpleClock instance.
*/
public function initClock(faceSize:Number = 200):void
{
// sets the invoice date to today’s date
var invoiceDate:Date = new Date();
// adds 30 days to get the due date
var millisecondsPerDay:int = 1000 * 60 * 60 * 24;
var dueDate:Date = new Date(invoiceDate.getTime() + (30 * millisecondsPerDay));
var oneHourFromNow:Date = new Date(); // starts at the current time
oneHourFromNow.setTime(oneHourFromNow.getTime() + millisecondsPerHour);
// Creates the clock face and adds it to the Display List
face = new AnalogClockFace(Math.max(20, faceSize));
face.init();
addChild(face);
// Draws the initial clock display
face.draw();
// Creates a Timer that fires an event once per second.
ticker = new Timer(1000);
// Designates the onTick() method to handle Timer events
ticker.addEventListener(TimerEvent.TIMER, onTick);
// Starts the clock ticking
ticker.start();
}
/**
* Called once per second when the Timer event is received.
*/
public function onTick(evt:TimerEvent):void
{
// Updates the clock display.
face.draw();
}
}
}
AlarmClock类
AlarmClock
package com.example.programmingas3.clock
{
import mx.core.UIComponent;
public class AlarmClock extends SimpleClock
{
import com.example.programmingas3.clock.AnalogClockFace;
import flash.events.TimerEvent;
import flash.utils.Timer;
public var alarmTime:Date;
public var alarmMessage:String;
/**
* The Timer that will be used for the alarm.
*/
public var alarmTimer:Timer;
public static var MILLISECONDS_PER_DAY:Number = 1000 * 60 * 60 * 24;
/**
* Instantiates a new AlarmClock of a given size
*/
public override function initClock(faceSize:Number = 200):void
{
super.initClock(faceSize);
alarmTimer = new Timer(0, 1);
alarmTimer.addEventListener(TimerEvent.TIMER, onAlarm);
}
/**
* Sets the time at which the alarm should go off.
* @param hour The hour portion of the alarm time
* @param minutes The minutes portion of the alarm time
* @param message The message to display when the alarm goes off.
* @return The time at which the alarm will go off.
*/
public function setAlarm(hour:Number = 0, minutes:Number = 0, message:String = "Alarm!"):Date
{
this.alarmMessage = message;
var now:Date = new Date();
// create this time on today's date
alarmTime = new Date(now.fullYear, now.month, now.date, hour, minutes);
// determine if the specified time has already passed today
if (alarmTime <= now)
{
alarmTime.setTime(alarmTime.time + MILLISECONDS_PER_DAY);
}
// reset the alarm timer if it's currently set
alarmTimer.reset();
// calculate how many milliseconds should pass before the alarm should
// go off (the difference between the alarm time and now) and set that
// value as the delay for the alarm timer
alarmTimer.delay = Math.max(1000, alarmTime.time - now.time);
alarmTimer.start();
return alarmTime;
}
/**
* Called when the Timer event is received
*/
public function onAlarm(event:TimerEvent):void
{
trace("Alarm!");
var alarm:AlarmEvent = new AlarmEvent(this.alarmMessage);
this.dispatchEvent(alarm);
}
}
}
package com.example.programmingas3.clock
{
import mx.core.UIComponent;
public class AlarmClock extends SimpleClock
{
import com.example.programmingas3.clock.AnalogClockFace;
import flash.events.TimerEvent;
import flash.utils.Timer;
public var alarmTime:Date;
public var alarmMessage:String;
/**
* The Timer that will be used for the alarm.
*/
public var alarmTimer:Timer;
public static var MILLISECONDS_PER_DAY:Number = 1000 * 60 * 60 * 24;
/**
* Instantiates a new AlarmClock of a given size
*/
public override function initClock(faceSize:Number = 200):void
{
super.initClock(faceSize);
alarmTimer = new Timer(0, 1);
alarmTimer.addEventListener(TimerEvent.TIMER, onAlarm);
}
/**
* Sets the time at which the alarm should go off.
* @param hour The hour portion of the alarm time
* @param minutes The minutes portion of the alarm time
* @param message The message to display when the alarm goes off.
* @return The time at which the alarm will go off.
*/
public function setAlarm(hour:Number = 0, minutes:Number = 0, message:String = "Alarm!"):Date
{
this.alarmMessage = message;
var now:Date = new Date();
// create this time on today's date
alarmTime = new Date(now.fullYear, now.month, now.date, hour, minutes);
// determine if the specified time has already passed today
if (alarmTime <= now)
{
alarmTime.setTime(alarmTime.time + MILLISECONDS_PER_DAY);
}
// reset the alarm timer if it's currently set
alarmTimer.reset();
// calculate how many milliseconds should pass before the alarm should
// go off (the difference between the alarm time and now) and set that
// value as the delay for the alarm timer
alarmTimer.delay = Math.max(1000, alarmTime.time - now.time);
alarmTimer.start();
return alarmTime;
}
/**
* Called when the Timer event is received
*/
public function onAlarm(event:TimerEvent):void
{
trace("Alarm!");
var alarm:AlarmEvent = new AlarmEvent(this.alarmMessage);
this.dispatchEvent(alarm);
}
}
}
AlarmEvent类
AlarmEvent
package com.example.programmingas3.clock
{
import flash.events.Event;
/**
* This custom Event class adds a message property to a basic Event.
*/
public class AlarmEvent extends Event
{
/**
* The name of the new AlarmEvent type.
*/
public static const ALARM:String = "alarm";
/**
* A text message that can be passed to an event handler
* with this event object.
*/
public var message:String;
/**
* Constructor.
* @param message The text to display when the alarm goes off.
*/
public function AlarmEvent(message:String = "ALARM!")
{
super(ALARM);
this.message = message;
}
/**
* Creates and returns a copy of the current instance.
* @return A copy of the current instance.
*/
public override function clone():Event
{
return new AlarmEvent(message);
}
/**
* Returns a String containing all the properties of the current
* instance.
* @return A string representation of the current instance.
*/
public override function toString():String
{
return formatToString("AlarmEvent", "type", "bubbles", "cancelable", "eventPhase", "message");
}
}
}
package com.example.programmingas3.clock
{
import flash.events.Event;
/**
* This custom Event class adds a message property to a basic Event.
*/
public class AlarmEvent extends Event
{
/**
* The name of the new AlarmEvent type.
*/
public static const ALARM:String = "alarm";
/**
* A text message that can be passed to an event handler
* with this event object.
*/
public var message:String;
/**
* Constructor.
* @param message The text to display when the alarm goes off.
*/
public function AlarmEvent(message:String = "ALARM!")
{
super(ALARM);
this.message = message;
}
/**
* Creates and returns a copy of the current instance.
* @return A copy of the current instance.
*/
public override function clone():Event
{
return new AlarmEvent(message);
}
/**
* Returns a String containing all the properties of the current
* instance.
* @return A string representation of the current instance.
*/
public override function toString():String
{
return formatToString("AlarmEvent", "type", "bubbles", "cancelable", "eventPhase", "message");
}
}
}
页面AS脚本
Code
import com.example.programmingas3.clock.AlarmEvent;
public function initApp():void
{
clock.addEventListener(AlarmEvent.ALARM, onAlarm);
// Adds 60 seconds to the current time and preloads the alarm fields
var alarmTime:Date = new Date();
alarmTime.setTime(alarmTime.time + 60000);
hourNs.value = alarmTime.hours;
minuteNs.value = alarmTime.minutes;
}
public function setAlarm():void
{
var alarmTime:Date = clock.setAlarm(hourNs.value, minuteNs.value, messageTxt.text);
alarmTimeTxt.text = "Alarm Time:" + alarmTime.hours + ":" + padZeroes(alarmTime.minutes.toString());
}
public function onAlarm(evt:AlarmEvent):void
{
alarmTimeTxt.text = evt.message;
}
public function padZeroes(numStr:String, desiredLength:uint = 2):String
{
if (numStr.length < desiredLength)
{
for (var i:uint = 0; i < (desiredLength - numStr.length); i++)
{
numStr = "0" + numStr;
}
}
return numStr;
}
import com.example.programmingas3.clock.AlarmEvent;
public function initApp():void
{
clock.addEventListener(AlarmEvent.ALARM, onAlarm);
// Adds 60 seconds to the current time and preloads the alarm fields
var alarmTime:Date = new Date();
alarmTime.setTime(alarmTime.time + 60000);
hourNs.value = alarmTime.hours;
minuteNs.value = alarmTime.minutes;
}
public function setAlarm():void
{
var alarmTime:Date = clock.setAlarm(hourNs.value, minuteNs.value, messageTxt.text);
alarmTimeTxt.text = "Alarm Time:" + alarmTime.hours + ":" + padZeroes(alarmTime.minutes.toString());
}
public function onAlarm(evt:AlarmEvent):void
{
alarmTimeTxt.text = evt.message;
}
public function padZeroes(numStr:String, desiredLength:uint = 2):String
{
if (numStr.length < desiredLength)
{
for (var i:uint = 0; i < (desiredLength - numStr.length); i++)
{
numStr = "0" + numStr;
}
}
return numStr;
}
运行结果:
作者:洞庭散人
出处:http://phinecos.cnblogs.com/
本博客遵从Creative Commons Attribution 3.0 License,若用于非商业目的,您可以自由转载,但请保留原作者信息和文章链接URL。
posted on 2007-11-19 22:26 Phinecos(洞庭散人) 阅读(4261) 评论(3) 编辑 收藏 举报