gpt4 book ai didi

java - 实时更新 ListView JavaFX

转载 作者:行者123 更新时间:2023-12-01 10:55:54 24 4
gpt4 key购买 nike

我有课:

public class Friends implements Runnable{
private ObservableList<String> friendsList;

public Friends() {
this.friendsList = FXCollections.observableArrayList();
}

public ObservableList<String> getList(){
return friendsList;
}
public void start(){
//run thread here
}
@Override
public void run() {
//update friendList here
}

}

在 Controller 中我这样写:

Friends vf = new Friends();
ListView_1.setItems(vf.getList());
vf.start();

之后 ListView 每秒更新一次,但我有这样的异常(exception):线程“Thread-5”中的异常 java.lang.IllegalStateException:不在 FX 应用程序线程上;当前线程 = 线程 5。......

读完手册后,我明白我们需要在 FX 线程中刷新 UI。我使用了 Platform.runLater(),但 UI 在流结束时速度变慢。

抱歉我的英语不好。

最佳答案

很可能您的 Friends.run 在单独的线程上运行并在那里更新 FriendsList。但这是不允许的。您必须使用Platform.runLater(() -> { friendsList.setAll(newValue); })更新FX应用程序线程上的friendList .

您可以在后台线程中构建 newValue,但设置 FriendsList 必须在 FX 应用程序线程上完成。

关于java - 实时更新 ListView JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33614564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com