JavaFX: How to Update VBox without notice of user

1.3k views Asked by At

I am making a chat application where chat is stored in MYSQL and periodically fetched in application.

I fetch chat from database, I iterate over messages and put one by one in VBox. Before putting this I've to clear VBox to avoid duplicate messages shown. I've used another thread using executor and scheduled it to do so after every 2 seconds.

The effect of clearing VBox and putting the messages is causing issues as VBox is first cleared then messages are inserted and keeps going on after every 2 seconds.

Is there any solution so that this effect is not noticeable.

I tried on the same thread as of javafx and it worked, delay between clearing and inserting messages is not noticeable but only for few number of messages. As there are large number of messages therefore iteration over them will cause the GUI to freeze.

1

There are 1 answers

2
fabian On BEST ANSWER

Use a GUI element where the number of nodes does not increase with the number of elements.

E.g. You could use ListView/TableView or write a similar control that only shows children that are visible. (Behavior described in the javadocs for Cell).

A ListView<Message> messageList (where Message is a class containing the data for a single message; Appropriate Message.toString implementation or cellFactory required) could be refreshed like this from a non-application thread:

final Message[] messages = retrieveMessages();
Platform.runLater(() -> messageList.getItems().setAll(messages));

You could also reduce the amount of data needed to be transfered by e.g. adding a timestamp to the rows of the table containing the messages indicating the time it was created and only retrieving those messages that have been modified since the last time the data was retrieved which removes the need to replace the whole data set and allows you to add only new messages, e.g.

final Message[] messages = retrieveNewMessages();
Platform.runLater(() -> messageList.getItems().addAll(messages));