附加於任何 Displayable (Form、List、TextBox) 頂部,單行滾動顯示。
Ticker ticker = new Ticker("歡迎來到 J2ME 世界!這是一條滾動訊息...");
form.setTicker(ticker);
TextBox txtBox = new TextBox("標題", null, 200, TextField.ANY);
// 參數:標題、初始內容、最大字元數、輸入限制
txtBox.addCommand(exitCmd);
txtBox.setCommandListener(this);
display.setCurrent(txtBox);
// 取得用戶輸入
String input = txtBox.getString();
注意:若指定初始內容,最大字元數必須 ≥ 內容長度,否則運行時錯誤。
public void commandAction(Command c, Displayable d) {
if (c == getCmd) {
Form result = new Form("輸入內容");
result.append(txtBox.getString());
result.addCommand(exitCmd);
display.setCurrent(result);
}
}
Date now = new Date();
long timestamp = now.getTime(); // 毫秒級時間戳 (自 1970-01-01)
form.append("當前時間戳: " + timestamp);
TimeZone tz = TimeZone.getDefault();
String[] ids = TimeZone.getAvailableIDs(); // 所有可用時區 ID
for (String id : ids) form.append(id + " ");
form.append("當前時區: " + tz.getID());
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1; // 0-based
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int dow = cal.get(Calendar.DAY_OF_WEEK); // 1=Sunday
// 日期運算
cal.add(Calendar.DAY_OF_MONTH, 7); // 一週後
cal.roll(Calendar.MONTH, 1); // 月份滾動(不改年份)
// 格式化輸出 (需自行組合或用 SimpleDateFormat - J2ME 子集可能不支援)
String formatted = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
package fancy.test;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
public class DateTimeDemo extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCmd = new Command("Exit", Command.EXIT, 1);
protected void startApp() {
display = Display.getDisplay(this);
form = new Form("日期時間資訊");
// 1. Date
Date now = new Date();
form.append("時間戳: " + now.getTime() + "\n");
// 2. TimeZone
TimeZone tz = TimeZone.getDefault();
form.append("當前時區: " + tz.getID() + "\n");
form.append("可用時區數: " + TimeZone.getAvailableIDs().length + "\n");
// 3. Calendar
Calendar cal = Calendar.getInstance();
form.append("年: " + cal.get(Calendar.YEAR) + "\n");
form.append("月: " + (cal.get(Calendar.MONTH)+1) + "\n");
form.append("日: " + cal.get(Calendar.DAY_OF_MONTH) + "\n");
form.append("時: " + cal.get(Calendar.HOUR_OF_DAY) + "\n");
form.append("分: " + cal.get(Calendar.MINUTE) + "\n");
form.append("秒: " + cal.get(Calendar.SECOND) + "\n");
form.append("星期: " + cal.get(Calendar.DAY_OF_WEEK) + "\n");
form.addCommand(exitCmd);
form.setCommandListener(this);
display.setCurrent(form);
}
// ... commandAction, pauseApp, destroyApp 標準實作
}
SimpleDateFormat:CLDC 1.0/1.1 不包含格式化類,需手動組合字串Calendar.getInstance() 取得具體實現 (通常是 GregorianCalendar)getAvailableIDs() 僅返回裝置支援的Date.getTime() 回傳 long,適合持久化與比較