willian ver valem
willian ver valem

Reputation: 395

javafx thread to update a listview

I'm trying to do a simple chat application on javafx my actual problem is the thread to insert updates into a observablelist and set it on a listview

the code im using :

                  String message_reçu;
    try {
        out = new PrintWriter(socket.getOutputStream());
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while (true) {
            message_reçu = in.readLine();
            if (message_reçu != null) {
                messagesReçus.add(message_reçu);  
            }
            if (message_reçu.equals("QUIT")) {
                break;
            }
        }

       in.close();
       out.close();
        socket.close();

I did this inside of a runnable class and once the server fire a msg the thread insert the msg on the list and shows on the listview but the thread dies instead of keep the work

I did a search on it and every one says to use a runlater but I’m completely lost there I did declare a runlater but I’m not sure how to execute it so any help is welcome

Thanks

Upvotes: 1

Views: 2920

Answers (1)

jewelsea
jewelsea

Reputation: 159341

Other Answers

This question is largely a duplicate of the following questions, so also refer to the answers to those:

Solution

Your question is little more specific than those though, so I'll provide some extra info.

For your particular code you want to wrap the add call in Platform.runLater:

Platform.runLater(new Runnable() {
  public void run() {
    messagesReçus.add(message_reçu);
  }
});

Everything else in your example stays as it is.

Background Information

JavaFX UI updates must be made on the JavaFX application thread or there is a high likelihood that your program will malfunction in unexpected ways.

The ListView control listens for changes to the ObservableList backing the ListView cell values. When that list changes, a UI update is immediately triggered on the thread the originally updated the list.

Once you wrap the list modifications in Platform.runLater, you ensure that the subsequently triggered UI update is performed on the JavaFX application thread rather than your user thread.

Upvotes: 5

Related Questions