我有课:
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
}}
在控制器中,我这样写:
Friends vf = new Friends();
ListView_1.setItems(vf.getList());
vf.start();在此之后,ListView每秒钟更新一次,但我有这样的异常:线程" Thread-5“中的异常: java.lang.IllegalStateException:不在FX应用程序线程上;currentThread =Thread-5。.
阅读了手册后,我了解到我们需要在FX线程中刷新UI。我使用了Platform.runLater(),但是UI在流的末尾减慢了。
为我糟糕的英语感到抱歉。
发布于 2015-11-10 10:11:29
您的Friends.run很可能运行在一个单独的线程上,并在那里更新friendsList。但这是不允许的。必须使用friendList更新FX应用程序线程上的Platform.runLater(() -> { friendsList.setAll(newValue); })。
您可以在后台线程中构建newValue,但是必须在FX应用程序线程上设置friendsList。
发布于 2016-05-17 04:39:54
首先,创建一个执行好友列表更新的任务类。
public class UpdateFriendsTask extends Task<Void>{
public ObjectProperty<ObservableList<String>> friendsProperty = new SimpleObjectProperty<>();
public ObservableList<String> friendsList;
public UpdateFriendsTask (ObservableList<String> friendsList) {
this.friendsList = friendsList;
friendsProperty.setValue(friendsList);
}
@Override
public Void call () throws Exception {
// parallel task to update friends list
// friendsList.add(...) ....
// friendsProperty.setValue(friendsList);
// maybe fetching from a datasource or web service
}
}并将以下代码添加到主代码中
// create a list of friends
ObservableList<String> friends = FXCollections.observableArrayList("John", "....");
//create listview to contain friends
ListView listView = new ListView();
// create instance of UpdateFriendsTask to update friends
UpdateFriendsTask friendsUpdateTask = UpdateFriendsTask(friends);
// bind friendsProperty to listView items property
listView.itemsProperty().bind(friendsUpdateTask.friendsProperty);
friendsUpdateTask.start();https://stackoverflow.com/questions/33614564
复制相似问题