I have a list of java bean objects that I would like to display in a ListView control. By default, ListView uses the toString method.
How to determine which property to use for rendering in a ListView?
I want to achieve the same functionality as in TableView, in the Property Code in this code can be achieved:
@FXML
private TableView<Person> mainTableView;
TableColumn<Person,String> personColumn = new TableColumn<>("Name");List
personColumn.setCellValueFactory(new PropertyValueFactory("name"));
mainTableView.getColumns().add(personColumn);
Edit
There seems to be no easy (out of the box) solution. Based on the code from James_D, I created a generic class to solve this problem. It completes the PropertyValueFactory - note that PropertyValueFactory first looks for the [NAME] Property () method, trying to get the observable only when it is not found, it tries to access the standard bean properties.
public class PropertyValueFactoryWrapperCellFactory<T> implements Callback<ListView<T>, ListCell<T>> {
private final PropertyValueFactory<T, String> pvf;
public PropertyValueFactoryWrapperCellFactory(String propertyName) {
super();
pvf = new PropertyValueFactory(propertyName);
}
@Override
public ListCell<T> call(ListView<T> param) {
return new ListCell<T>() {
@Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
textProperty().unbind();
if (item == null) {
return;
}
TableColumn.CellDataFeatures<T, String> cdf = new TableColumn.CellDataFeatures<>(null, null, item);
textProperty().bind(pvf.call(cdf));
}
};
}
}
Using:
@FXML
private ListView<Person> mainListView;
mainListView.setCellFactory(new PropertyValueFactoryWrapperCellFactory("name"));