繁体   English   中英

实时更新ListView JavaFX

[英]Live updating ListView JavaFX

我有课:

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 =线程5。 .....

阅读手册后,我了解到我们需要刷新FX线程中的UI。 我使用了Platform.runLater(),但是在流的结尾,UI变慢了。

对不起,我的英语不好。

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

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

首先创建一个任务类,执行您的好友列表的更新

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM