AS3 的 SimpleButton 内加入文字后,该如何用程式修改文字呢 ? 还记得 AS2 的程式写法是
myBtn.label.text = "button",非常简易的存取方式。而 AS3 程式存取写法是完全不一样的,因为跟 AS2 的按钮设计
方法完全不一样。若是在 AS3 中用 myBtn.label 会发现不能存取。
假设您了解 SimpleButton 的类别用法,SimpleButton 有三个状态,upState、overState、
downState。
要存取文字应该要这样写
(((myBtn.upState as Sprite).getChildAt(1)) as TextField).text = "1";
(((myBtn.overState as Sprite).getChildAt(1)) as TextField).text = "2";
(((myBtn.downState as Sprite).getChildAt(1)) as TextField).text = "3";
getChildAt(1) 是存取上图参考图片 label 图层的动态文字物件
getChildAt(0) 是存取上图参考图片 graphic 图层的 Shape 物件
AS3有了按钮类:SimpleButton ,可以为四种状态分别指定不同的 DisplayObject 。但是 SimpleButton 没有继承 DisplayObjectContainer 类,也就是不能给它添加其他的 child 。如果要创建一个带文字的 Button 怎么办?两种方案:
- 方案一:把文字加到每种 state 里。因为 Shape 也没有继承 DisplayObjectContainer 类,要添加文字 state 就要用 Sprite 。优点是每种状态可以有不同的文字颜色、大小、位置等。缺点是不方便改文字内容。
- 方案二:把 SimpleButton 和 TextField 一起放到一个 Sprite 里。这样 SimpleButton 的 state 可以用 Shape 以节省内存空间。优缺点和方案一相反。[feel_good]
看看 代码 和演示:
创建一个按钮很简单,为它的四种状态分别指定一个 DisplayObject 就可以了:
btn
=
new
SimpleButton
()
;
btn
.
name
=
"
btn
"
;
btn
.
downState
=
new
BtnStatusShape2
(
downColor
,
w
,
h
)
;
btn
.
overState
=
new
BtnStatusShape2
(
overColor
,
w
,
h
)
;
btn
.
upState
=
new
BtnStatusShape2
(
upColor
,
w
,
h
)
;
btn
.
hitTestState
=
btn
.
upState
;
addChild
(
btn
)
;
注意必须指定 hitTestState ,就是Flash IDE里创建 Button 时的 hit 帧,响应鼠标事件的区域,如果没有它按钮就失去作用了。一般设置它和 upState 一样就可以了。
第二种方案的每种 state 都是一个 Shape(→ DisplayObject → EventDispatcher → Object):
internal
class
BtnStatusShape2
extends
Shape
{
public
function
BtnStatusShape2
(
bgColor
:
uint
,
w
:
uint
,
h
:
uint
)
{
graphics
.
lineStyle
(
1
,
0
x000000
,
0.8
)
graphics
.
beginFill
(
bgColor
,
0.8
)
;
graphics
.
drawRoundRect
(
0
,
0
,
w
,
h
,
8
)
;
graphics
.
endFill
()
;
}
}
方案一没有什么好说的。方案二如果想让 btn 响应鼠标事件可以重写装载它的 Sprite 的 addEventListener 方法:
public
override
function
addEventListener
(
type
:
String
,
listener
:
Function
,
useCapture
:
Boolean
=
false
,
priority
:
int
=
0
,
useWeakReference
:
Boolean
=
false
)
:
void
{
btn
.
addEventListener
(
type
,
listener
)
;
}
要重写继承自父类的方法必须使用 override 关键字。而且重写的方法必须有父类方法完全相同的参数名称、数量和类型。
当然方案二也可以通过监听 MOUSE_OVER、MOUSE_OUT、CLICK 等 MouseEvent 来改变不同状态的文本显示