我的应用程序中有任务,我不知道它是如何从这个任务返回的。
public class TimeManager extends Service<String> {
@Override
protected Task<String> createTask() {
return new Task<String>() {
@Override
protected String call() throws Exception {
String txt = null;
while (!isCancelled()) {
try {
txt = "some txt";
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
return txt;
}
};
}
Run Code Online (Sandbox Code Playgroud)
在主类中:
TimeManager time = new TimeManager();
time.start();
time.getValue();
Run Code Online (Sandbox Code Playgroud)
时间总是返回空值。我该怎么做才能返回值?线程运行良好,我可以将数据从线程发送到应用程序
您的任务不发布中间更新。此外Service用于在后台线程中运行任务以避免阻塞 JavaFX 应用程序线程。因此,如果您在启动服务后直接访问该值,则可能不会分配该值。value在分配数据时,最好使用该属性的绑定或侦听器来检索数据。
public class TimeManager extends Service<String> {
@Override
protected Task<String> createTask() {
return new Task<String>() {
int i = 0;
@Override
protected String call() throws Exception {
String txt = null;
while (!isCancelled()) {
txt = Integer.toString(++i);
updateValue(txt); // publish new value
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
return txt;
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
TimeManager time = new TimeManager();
label.textProperty().bind(time.valueProperty());
time.start();
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,可能不需要服务,因为您只运行一个任务。使用运行Task实例new Thread(task).start()实际上可能就足够了。
此外,还有更好的选项可以安排 GUI 的快速重复更新,请参阅JavaFX 定期后台任务
| 归档时间: |
|
| 查看次数: |
356 次 |
| 最近记录: |