javafx StringConverter最后一个对象 [英] javafx StringConverter Last Object
问题描述
我在创建可编辑的ListView时遇到一些问题。
i have a little problem for creating an editable ListView.
所以我有一个带有两个字段的City Class: id
和 name
,我已经从数据库中创建了一个ObservableList,并将它分配给我的ListView,我创建了我的cellFactory:
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;
}
});
我想知道是否可以获取单元格中当前值的引用(City)当 fromString
被调用时
I want to know if its possible to get a reference of the current value in the cell(City) when fromString
is called
我想这样做是为了允许用户更改城市名称而不必更改其ID字段。
i want to do that to allow user to change City name without having to change its Id field.
推荐答案
如果先创建单元格,然后创建转换器,则可以引用单元格。转换器中的getItem()
。以下似乎有效:
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 ;
});
这篇关于javafx StringConverter最后一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!