The simplest cell factory is TextFieldListCell. It allows us to double-click on any item in the ListView and set a new value, which will be automatically be reflected in the corresponding ObservableList. Refer to the following code:
// chaptep10/list/TextFieldListCellDemo.java
ObservableList<Integer> items = FXCollections.observableArrayList(
100, 200, 500, 1000);
ListView<Integer> list = new ListView<>(items);
list.setEditable(true);
list.setCellFactory(TextFieldListCell.forListView(new
IntegerStringConverter()));
items.addListener((ListChangeListener.Change<? extends Integer> change) -> {
// this will write something like
// { [500] replaced by [600] at 2 }
System.out.println(change);
});
stage.setTitle("TextFieldListCell Demo");
stage.setScene(new Scene(new StackPane(list), 200, 200));
stage.show();
Now, you can double-click on any field to get an editing UI:
Note that our ListView this time holds Integer. You don't need to do anything extra to make ListView show them; by default, it will use toString(). But, to edit values, we need to provide a converter to and from String, because TextField works with Strings, hence the IntegerStringConverter parameter.
Due to API restrictions, you need to provide a converter even for String-based lists. It's called DefaultStringConverter and does essentially nothing.