How to update tableview items outside JavaFX thread
•
Java
I have a table view of list user friends. I need to update it every 5 seconds with the data I retrieve from the database
This is the code I use:
Main.java private List<Friend> userFriends;
FX controller:
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();
}
Friends are database models Friendwrapper is an object for table rows
But I get the IllegalStateException: the FX application thread friendlist clear();
How do I change a tableview item from a thread running in the background?
Solution
You should use the task class instead of the fast platform Runlater() hacker attack:
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 start this as a thread, for example:
new Thread(new LoadFriendsTask()).start()
For further reference:
> JavaFX – Background Thread for SQL Query > How can I do asynchrous database in JavaFX > Multithreading in JavaFX
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
