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 毫秒
显示文本播放器
等待 1000 毫秒
显示 text3player
线程完成。
屏幕等待 this.duration + 1000 毫秒并立即显示所有标签。
我尝试使用 runnable 并调用 .invokeLater 或 .invokeAndWait 但我仍然得到相同的行为,即使我像上面那样使用 synchronized 变得肮脏它仍然不起作用。
有谁知道我如何一次显示每个标签?
谢谢!
最佳答案
尝试在 sleep 语句之间移动同步......也许它没有出现是因为你已经获得了锁并且 UI 线程在你 sleep 时无法更新。
您是否在线程 hibernate 时看到 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");
}
}
}
}
关于java - 如何从线程更新黑莓 UI 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2569468/