在 Java FX 工作线程中不断更新 UI
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20497845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Constantly Update UI in Java FX worker thread
提问by Killerpixler
I have Label labelin my FXML Application.
我Label label在我的 FXML 应用程序中有。
I want this label to change once a second. Currently I use this:
我希望这个标签每秒更改一次。目前我使用这个:
Task task = new Task<Void>() {
@Override
public Void call() throws Exception {
int i = 0;
while (true) {
lbl_tokenValid.setText(""+i);
i++;
Thread.sleep(1000);
}
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
However nothing is happening.
然而,什么也没有发生。
I don't get any errors or exceptions.
I don't need the value I change the label to in my main GUI thread so I don't see the point in the updateMessageor updateProgressmethods.
我没有收到任何错误或异常。我不需要在主 GUI 线程中将标签更改为的值,因此我看不到updateMessageorupdateProgress方法中的要点。
What is wrong?
怎么了?
采纳答案by zhujik
you need to make changes to the scene graph on the JavaFX UI thread. like this:
您需要对 JavaFX UI 线程上的场景图进行更改。像这样:
Task task = new Task<Void>() {
@Override
public Void call() throws Exception {
int i = 0;
while (true) {
final int finalI = i;
Platform.runLater(new Runnable() {
@Override
public void run() {
label.setText("" + finalI);
}
});
i++;
Thread.sleep(1000);
}
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
回答by dmolony
Cosmetic change to Sebastian's code.
对 Sebastian 代码的外观更改。
while (true)
{
final int finalI = i++;
Platform.runLater ( () -> label.setText ("" + finalI));
Thread.sleep (1000);
}

