J2ME 標準 StringItem 無法自動滾動過長文本。需在標題欄或表單中實現「文字超寬時自動左右滾動」的跑馬燈效果。
moveX)。left ~ right)時,啟動滾動;否則靜止顯示。moveX += 1,超出右邊界則重置至初始 tempX 形成循環。isFocused)時啟動,釋放焦點即停止。class MoveItemContentTask implements Runnable {
private boolean ismoving;
private int moveX, tempX, left, right;
public void movingPain(int x, int y, int leftBorder, int rightBorder,
boolean isFocused, Graphics g) {
moveX = tempX = x;
left = leftBorder; right = rightBorder;
ismoving = isFocused;
paintContent(moveX, y, left, right, g); // 實際繪製調用
}
public void run() {
changeX(moveX);
try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); }
}
private void changeX(int x) {
if (ismoving) {
if (x < left || x > right) x = tempX;
else x += 1;
}
}
}
Canvas 或 CustomItem 的 paint() 中調用 movingPain()。paintContent() 需自行實現:g.drawString(text, moveX, y, Graphics.TOP | Graphics.LEFT) 並設置裁剪區 g.setClip(left, 0, right-left, height)。pointerPressed、keyPressed)更新 ismoving 狀態。Timer + TimerTask 替代手動 sleep,控制更精準。Font.stringWidth(text),僅在 width > visibleWidth 時啟動線程,節省資源。以輕量級線程驅動座標位移,配合裁剪區繪製,即可在受限的 J2ME 環境實現流暢的跑馬燈效果。核心在於「狀態機控制 + 週期性重繪」的簡潔模式。