I'm getting the following exception when trying to update ListView from a different thread (see code below). What am I doing wrong?
---------
Exception in thread "Thread" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:189)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:321)
...
---------
package test;
import java.util.ArrayList;
import java.util.List;
import java.lang.Thread;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.paint.Color;
import javafx.collections.SortedList;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
public class test extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, 200, 200, Color.BLACK);
primaryStage.setScene(scene);
SimpleListView slv = new SimpleListView(root);
primaryStage.setVisible(true);
UpdateWrapper uw = new UpdateWrapper(slv);
Thread t = new Thread(uw, "Thread");
t.start();
}
}
class SimpleListView{
ObservableList<String> observedList;
public SimpleListView(Group parent) {
final ListView<String> listView = new ListView<String>();
observedList = FXCollections.observableArrayList();
SortedList<String> sortedList = new SortedList<String>(observedList);
listView.setItems(sortedList);
parent.getChildren().add(listView);
addListElement("From FX thread");
}
void addListElement(String s){
observedList.add(s);
}
}
class UpdateWrapper implements Runnable{
SimpleListView slv1;
public UpdateWrapper(SimpleListView slv){
slv1 = slv;
}
public void run (){
for (int i = 0; i < 10; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
slv1.addListElement("From other thread : " + i);
}
}
}