java – 如何从线程更新blackberry 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();
}
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,但我仍然得到相同的行为,即使我像上面那样使用synchronized变脏,它仍然不起作用.
有谁知道我如何一次显示每个标签?
谢谢!
解决方法:
尝试在sleep语句之间移动同步…也许它没有显示,因为你已经获得了锁定,并且在你睡觉时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");
}
}
}
}
标签:java,uilabel,multithreading,blackberry 来源: https://codeday.me/bug/20190607/1191177.html