2011-04-19 83 views
2

我想用一個每秒更新一次標籤的時間(所以它顯示倒計時),但它只有 似乎是「滴答」一次,我無法弄清楚我是什麼做錯了!黑莓計時器不啓動TimerTask

public class Puzzle extends UiApplication { 

public static void main(String[] args) { 
    Puzzle puzzle = new Puzzle(); 
    puzzle.enterEventDispatcher(); 

} 

public Puzzle() { 


    pushScreen(new PuzzleScreen()); 
} 

} 

class PuzzleScreen extends MainScreen { 
LabelField timerLabel; 
Timer timer; 
public static int COUNT = 0; 

public PuzzleScreen() { 

    //set up puzzle 

    VerticalFieldManager vfm = new VerticalFieldManager(); 
    add(vfm); 
    timerLabel = new LabelField(); 
    timerLabel.setText("00:20"); 
    vfm.add(timerLabel); 

    StartTimer(); 

} 

void StartTimer() { 
    timer = new Timer(); 
    timer.schedule(new TimerTick(), 1000); 
} 
private class TimerTick extends TimerTask { 

    public void run() { 

     UiApplication.getUiApplication().invokeLater(new Runnable() { 
      public void run() { 

       timerLabel.setText((COUNT++) + ""); 
      } 

     }); 
    } 
} 

任何人都可以看到我做錯了什麼..?發生的所有事情是我的標籤get被設置爲「0」,然後不會改變。我在計時器tick類中運行了一個斷點,但我沒有看到它發射!

貝克斯

回答

2

你需要改變你的計時器的時間表()調用

timer.schedule(new TimerTick(), 0, 1000); 

您現在正在調用它的方式是說第二延遲後運行一次。這種方式表示現在和每秒運行它。你可能想使用

timer.scheduleAtFixedRate(new TimerTick(), 0, 1000); 

雖然,因爲這將確保平均您的TimerTask是跑每秒,而不是正常的作息時間()調用表示,將嘗試在等待第二個,然後執行,但它如果事情放慢速度,可能會落後。如果scheduleAtFixedRate()延遲,它將使多次調用比1秒延遲更快,因此它可以「趕上」。看看http://www.blackberry.com/developers/docs/5.0.0api/java/util/Timer.html#scheduleAtFixedRate(java.util.TimerTask,%20long,%20long)更詳細的解釋。

+0

就像您發佈它點擊了!哎呀!新來Java和缺少我的C#位!謝謝! – Bex 2011-04-19 16:45:22

+0

很高興幫助! – jprofitt 2011-04-19 17:00:43

+0

@jprofitt,我只想調用我的方法一次,所以這將是聲明? timer.schedule(new TimerTick(),1000); – 2011-09-06 12:35:12