01.
02.
package
net.L4cd.display
03.
{
04.
import
flash.events.Event;
05.
import
flash.events.TextEvent;
06.
import
flash.text.TextField;
07.
import
flash.utils.ByteArray;
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
public
class
TextFieldExt
extends
TextField
18.
{
19.
private
var
_maxChars:
int
= -
1
;
20.
public
function
TextFieldExt()
21.
{
22.
super
();
23.
24.
}
25.
override
public
function
get
maxChars():
int
26.
{
27.
return
_maxChars;
28.
}
29.
override
public
function
set
maxChars(value:
int
):
void
30.
{
31.
_maxChars = value;
32.
if
(maxChars<
0
)
33.
{
34.
removeEventListener(TextEvent.TEXT_INPUT,input);
35.
}
else
36.
{
37.
addEventListener(TextEvent.TEXT_INPUT,input);
38.
text = getTextByCharLength(text,maxChars);
39.
}
40.
}
41.
override
public
function
get
length():
int
42.
{
43.
return
getCharLength(text);
44.
}
45.
private
function
input(e:TextEvent):
void
46.
{
47.
48.
var
textField:TextField = e.currentTarget
as
TextField;
49.
var
temp:
String
= getTextByCharLength(e.text,maxChars - getCharLength(text) + getCharLength(selectedText));
50.
var
index:
int
= selectionBeginIndex;
51.
replaceText(selectionBeginIndex,selectionEndIndex,temp);
52.
setSelection(index+temp.length,index+temp.length);
53.
dispatchEvent(
new
Event(Event.CHANGE,
true
));
54.
e.preventDefault();
55.
}
56.
57.
58.
59.
60.
61.
private
function
getCharLength(txt:
String
):
int
62.
{
63.
var
byte:ByteArray =
new
ByteArray();
64.
byte.writeMultiByte(txt,
"gb2312"
);
65.
byte.position =
0
;
66.
return
byte.bytesAvailable;
67.
}
68.
69.
70.
71.
72.
73.
74.
private
function
getTextByCharLength(txt:
String
,length:
int
):
String
75.
{
76.
if
(length<
1
)
return
""
;
77.
var
byte:ByteArray =
new
ByteArray();
78.
byte.writeMultiByte(txt,
"gb2312"
);
79.
byte.position =
0
;
80.
return
byte.readMultiByte(Math.min(length,byte.bytesAvailable),
"gb2312"
);
81.
}
82.
}
83.
}