问题
i have a little problem for creating an editable ListView.
so i have a City Class with two field : id
and name
, i have created a ObservableList of cities from a database and assigned it to my ListView, and i have created my cellFactory :
@DatabaseTable(tableName = "city")
public class City {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
private String name;
public City() {}
}
citiesList.setCellFactory(new Callback<ListView<City>, ListCell<City>>() {
@Override
public ListCell<City> call(ListView<City> param) {
ListCell<City> cells = new TextFieldListCell<>(new StringConverter<City>() {
@Override
public String toString(City object) {
return object.getName().trim();
}
@Override
public City fromString(String string) {
// how to modify the object that was in the cell???
return null;
}
});
return cells;
}
});
I want to know if its possible to get a reference of the current value in the cell(City) when fromString
is called
i want to do that to allow user to change City name without having to change its Id field.
回答1:
If you create the cell first, then create the converter, you can reference cell.getItem()
in the converter. The following seems to work:
citiesList.setCellFactory(lv -> {
TextFieldListCell<City> cell = new TextFieldListCell<City>();
StringConverter<City> converter = new StringConverter<City>() {
@Override
public String toString(City city) {
return city.getName();
}
@Override
public City fromString(String string) {
City city = cell.getItem();
if (city == null) {
City newCity = new City();
newCity.setName(string);
return newCity;
} else {
city.setName(string);
return city ;
}
}
};
cell.setConverter(converter);
return cell ;
});
来源:https://stackoverflow.com/questions/32466780/javafx-stringconverter-last-object