Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example application showing how changing an item in a ListView changes its index
import java.io.IOException;
import java.util.Arrays;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Stage;
import javafx.util.Callback;
/**
* Demonstrate a bug in ListView where changing an item property modified the
* index. The {@link ObservableList} must have been created by calling
* {@link FXCollections#observableArrayList(Callback)} where the callback
* returns the property that is changed.
*
* @author Andy Till
*
*/
public class ListViewIndexChangesWhenItemUpdated extends Application {
/**
* Change this to speed up the change, although it is important to see the
* UI before the list item is modified.
*/
private static final int ITEM_CHANGE_DELAY = 2000;
public static void main(String[] args) throws IOException {
Application.launch(args);
}
@Override
public void start(Stage stage) throws Exception {
final ObservableList<Person> observableArrayList = FXCollections.observableArrayList(new Callback<Person, Observable[]>() {
@Override
public Observable[] call(Person myTreeData) {
return new Observable[] { myTreeData.nameProperty() };
}});
observableArrayList.addAll(Arrays.asList(new Person("Test"), new Person("Test2")));
ListView<Person> listView = new ListView<Person>();
listView.setItems(observableArrayList);
listView.getSelectionModel().select(0);
Scene scene = new Scene(listView, 800, 600);
stage.setScene(scene);
stage.show();
// modify the first list item after a delay without blocking the current
// thread
new Thread() {
@Override
public void run() {
try {
sleep(ITEM_CHANGE_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
Platform.runLater(new Runnable() {
@Override
public void run() {
observableArrayList.get(0).nameProperty().set("Changing");
}});
}
}.start();
}
private static class Person {
public Person(String name) {
this.name.set(name);
}
private final StringProperty name = new SimpleStringProperty();
public StringProperty nameProperty() {
return name;
}
@Override
public String toString() {
return nameProperty().get();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.