在 Flash 中做即時監控時,XMLSocket 可以接收伺服器推送過來的 XML 訊息。為了讓操作者一眼看出狀態,常會用動態文字搭配不同顏色。
Flash 的文字大致可分為靜態文字、動態文字與輸入文字。靜態文字適合固定標題;動態文字可在執行期由程式改變;輸入文字則供使用者填寫。這個案例主要使用動態文字。
下列程式片段示範如何解析 MESSAGE 節點,並依 type 屬性決定紅色或藍色。紅色代表錯誤,藍色代表正常。
function myOnXML(doc) {
var e = doc.firstChild;
Selection.setFocus("_root.txt");
Selection.setSelection(0, 0);
if (e != null && e.nodeName == "MESSAGE") {
if (e.attributes.type == "error") {
myTextFormat.color = "0xff0000";
txt.setNewTextFormat(myTextFormat);
txt.replaceSel("Error -- " + e.attributes.text + " -- " + e.attributes.time + newline);
} else if (e.attributes.type == "normal") {
myTextFormat.color = "0x0000ff";
txt.setNewTextFormat(myTextFormat);
txt.replaceSel("Normal -- " + e.attributes.text + " -- " + e.attributes.time + newline);
}
}
}
其中 replaceSel() 會把文字插入目前選取位置;搭配 Selection.setSelection(0, 0),可讓新訊息固定出現在文字方塊最上方。newline 則是 Flash 的換行常量。