2010-04-02 19 views
4
public class PlayText extends Thread { 

    private int duration; 
    private String text; 
    private PlayerScreen playerscrn; 

    public PlayText(String text, int duration) { 
     this.duration = duration; 
     this.text = text; 
     this.playerscrn = (PlayerScreen)UiApplication.getUiApplication().getActiveScreen(); 
    } 



    public void run() { 
     synchronized(UiApplication.getEventLock()) { 
      try{ 
       RichTextField text1player = new RichTextField(this.text, Field.NON_FOCUSABLE); 
       playerscrn.add(text1player); 
       playerscrn.invalidate(); 

       Thread.sleep(this.duration); 

       RichTextField text2player = new RichTextField("hahhaha", Field.NON_FOCUSABLE); 
       playerscrn.add(text2player); 
       playerscrn.invalidate(); 

       Thread.sleep(1000); 
       RichTextField text3player = new RichTextField("Done", Field.NON_FOCUSABLE); 
       playerscrn.add(text3player); 
       playerscrn.invalidate(); 

      }catch(Exception e){ 
      System.out.println("I HAVE AN ERROR"); 
      } 
     } 
    } 
} 

有了上面的代碼,我試圖創建一個小文本播放器。
而是把所有的文字標籤一個接一個,像

顯示text1player
等待this.duration毫秒
顯示text2player
等待1000毫秒
顯示text3player
線程中完成的。

屏幕等待this.duration + 1000毫秒並一次顯示所有標籤。 我嘗試了一個runnable並調用.invokeLater或.invokeAndWait,但我仍然得到相同的行爲,即使我像上面一樣使用同步來弄髒它仍然不起作用。
有誰知道我怎麼能一次顯示每個標籤?
謝謝!如何從線程更新黑莓UI項目?

回答

7

嘗試移動睡眠語句之間的同步...也許它沒有顯示出來,因爲您已經獲取了鎖定,並且在睡眠時UI線程無法更新。

當線程處於睡眠狀態時,您是否在UI中看到延遲或無響應?試試這個方法:

public class PlayText extends Thread { 

    private int duration; 
    private String text; 
    private PlayerScreen playerscrn; 

    public PlayText(String text, int duration) { 
     this.duration = duration; 
     this.text = text; 
     this.playerscrn = (PlayerScreen)UiApplication.getUiApplication().getActiveScreen(); 
    } 

    private void displayTextLabel(string textToDisplay){ 
     synchronized(UiApplication.getEventLock()) { 
      playerscrn.add(new RichTextField(textToDisplay, Field.NON_FOCUSABLE)); 
      playerscrn.invalidate(); 
     } 
    } 

    public void run() { 

      try{ 

       displayTextLabel(this.text); 
       Thread.sleep(this.duration); 

       displayTextLabel("hahhaha"); 
       Thread.sleep(1000); 

       displayTextLabel("Done"); 

      }catch(Exception e){ 
      System.out.println("I HAVE AN ERROR"); 
      } 
     } 
    } 
} 
+0

它的工作原理,謝謝! 我正在閱讀和閱讀BB文檔兩天了,我什麼都沒發現,stackoverflow保存了我的一些神經元。 – andreiursan 2010-04-02 22:45:09

+0

我曾經說過「google是你的朋友」,但自從我來到stackoverflow後,我決定說「stackoverflow是你最好的朋友!」 :) – Kiril 2010-04-02 22:51:27

+1

我不能同意更多:)。 – andreiursan 2010-04-02 23:18:41