re0603
re0603

Reputation: 387

Adding items to ListView in JavaFx... threading?

I'm trying to add a string to ListView in JavaFX whilst processing, but it keeps freezing my GUI.

I've tried the following threading - but can't seem to get it to work for a ListView.
Does anybody know how/have an example of how I can update a ListView in JavaFX whilst processing data?

new Thread(new Runnable() {
    @Override public void run() {
        for (int i=1; i<=1000000; i++) {
            final int counter = i;
            Platform.runLater(new Runnable() {
                @Override public void run() {
                    recentList.getItems().add(Integer.toString(counter));
                }
            });
        }
    }}).start();

Upvotes: 0

Views: 1198

Answers (3)

ItachiUchiha
ItachiUchiha

Reputation: 36722

Your GUI hangs because you are blocking the JavaFX application thread by calling Platform.runLater() continuously in your Thread.

You can perform a quick fix by adding a sleep statement inside your for-loop to avoid it.

for (int i=1; i<=1000000; i++) {
     final int counter = i;
     Platform.runLater(new Runnable() {
        @Override public void run() {
            recentList.getItems().add(Integer.toString(counter));
        }
     });
     // Add Sleep Time
     Thread.sleep(some milli seconds);
}

To use a more proper and advisable way, use an AnimationTimer, as shown in

JavaFX - Concurrency and updating label

Upvotes: 0

Andrei Olaru
Andrei Olaru

Reputation: 31

You can do the animation / ui update after adding those strings in the list or use Platform.runLater only once (not advisable):

Platform.runLater(new Runnable() {
  for (int i=1; i<=1000000; i++) {
        final int counter = i;

            @Override public void run() {
                recentList.getItems().add(Integer.toString(counter));
            }
     }
});

Upvotes: 0

VinceOPS
VinceOPS

Reputation: 2720

Using Platform.runLater() is the correct way to go. You could, also, store the String result from Integer.toString(counter) in the background thread (not the UI one). By the way, you should use String.valueOf (there is a thread on StackOverflow which talks about it).

I assume your UI is freezing because of the execution speed of the (very simple) loop.

You should also have a look at Concurrency in JavaFX

Upvotes: 1

Related Questions