ComboBox控件具有setConverter方法,有关示例,请参见JavaFX ComboBox - Display text but return ID on selection。我正在尝试使该问题的可接受答案与ListView控件一起使用。我在任何文档中都没有看到ListView类的setConverter方法。
@FXML private ListView<RowlvPqAttributes> lvPqAttributes;
//...
class RowlvPqAttributes {
private String ID;
private String text;
public RowlvPqAttributes(String ID, String text) {
setID(ID);
setText(text);
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
private void initlvPqAttributes() {
lvPqAttributes.setConverter(new StringConverter<RowlvPqAttributes>() {
@Override
public String toString(RowlvPqAttributes object) {
return object.getText();
}
@Override
public RowlvPqAttributes fromString(String string) {
return lvPqAttributes.getItems().stream().filter(ap ->
ap.getText().equals(string)).findFirst().orElse(null);
}
});
如果我接受建议的修复程序,则无济于事:
答案 0 :(得分:3)
对于使用ListView
方法配置显示的setCellFactory
,它们的工作方式不同
lvPqAttributes.setCellFactory(lv -> new ListCell<RowlvPqAttributes>() {
@Override
public void updateItem(RowlvPqAttributes row, boolean empty) {
super.updateItem(row, empty) ;
setText(empty ? null : row.getText());
}
}
要从所选项目中获取数据:
RowlvPqAttributes selected = lvPqAttributes.getSelectionModel().getSelectedItem();
String selectedID = selected.getID();
String selectedText = selected.getText();