如何更新JavaFX Thread之外的TableView项目 [英] How to update TableView items outside JavaFX Thread

查看:482
本文介绍了如何更新JavaFX Thread之外的TableView项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格视图,列出了用户的朋友,我需要每5秒更新一次数据,从数据库中检索数据。

I have a table view that lists user's friends and I need to update it every 5 seconds with data that I retrieve from database.

这是我使用的代码:

Main.java
   private List<Friend> userFriends;

fx控制器:

    ObservableList<FriendWrapper> friendList = FXCollections.observableList(
    new ArrayList<FriendWrapper>());

private void updateFriendList() {
    new Thread(new Runnable() {
        public void run() {
            while (Params.loggedUser != null) {
                Main.setUserFriends(Params.dao.listUserFriends(Params.loggedUser));
                friendList.clear();
                for (Friend friend : Main.getUserFriends()) {
                    friendList.add(new FriendWrapper(friend.getFriendName(), friend.getOnline(), friend.getFriendId(), friend.getWelcomeMessage()));
                }
                Params.dao.updateOnlineStatus(Params.loggedUser, 3);
                try {
                    Thread.sleep(1000 * 5); 
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }, "updateFriendList").start();
}

朋友是数据库模型。 FriendWrapper 是用于表行的对象。

Friend is database model. FriendWrapper is object used for table rows.

但是我得到 IllegalStateException:不在FX应用程序线程在线 friendList.clear();

如何更改

推荐答案

而不是快速 Platform.runLater( ) hack,你应该使用 任务 类:

Instead of a quick Platform.runLater() hack, you should probably make use of the Task class:

protected class LoadFriendsTask extends Task<List<FriendWrapper>>
{

    @Override
    protected List<FriendWrapper> call() throws Exception {

        List<Friend> database = new ArrayList<>(); //TODO fetch from DB
        List<FriendWrapper> result = new ArrayList<>();
        //TODO fill from database in result
        return result;
    }

    @Override
    protected void succeeded() {
        getTableView().getItems().setAll(getValue());
    }

}

您可以启动这个线程,例如:

You can launch this one as a Thread, for example:

new Thread(new LoadFriendsTask()).start()

进一步参考:

  • JavaFX - Background Thread for SQL Query
  • How can I do asynchrous database in JavaFX
  • Multithreading in JavaFX

这篇关于如何更新JavaFX Thread之外的TableView项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆