我想在没有输入密钥的情况下对ListCell
提交更改。
我有以下代码:
objetListview1.setEditable(true);
objetListview1.setItems(FXCollections.observableArrayList(observableSet2));
objetListview1.setEditable(true);
objetListview1.setCellFactory(lv -> {
TextFieldListCell<Typ> cell = new TextFieldListCell<Typ>();
StringConverter<Typ> converter = new StringConverter<Typ>() {
@Override
public String toString(Typ obj) {
return obj.getTyp();
}
@Override
public Typ fromString(String string) {
Typ obj = cell.getItem();
if (obj == null) {
Typ newObj = new Typ("");
newObj.setTyp(string);
return newObj;
} else {
obj.setTyp(string);
return obj;
}
}
};
cell.setConverter(converter);
return cell;
});
实际上使用此代码,我可以使用回车键进行更改。
请帮忙吗?
答案 0 :(得分:0)
我找到了解决问题的方法。
这是我的代码:
objetListview1.setCellFactory(lv -> new ListCell<Typ>() {
private TextField textField = new TextField() ;
{
textField.setOnAction(e -> {
commitEdit(getItem());
});
textField.focusedProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
if (!newValue) {
System.out.println("Commiting " + textField.getText());
commitEdit(getItem());
}
});
}
@Override
protected void updateItem(Typ person, boolean empty) {
super.updateItem(person, empty);
if (empty) {
setText(null);
setGraphic(null);
} else if (isEditing()) {
textField.setText(person.getTyp());
setText(null);
setGraphic(textField);
} else {
setText(person.getTyp());
setGraphic(null);
}
}
@Override
public void startEdit() {
super.startEdit();
textField.setText(getItem().getTyp());
setText(null);
setGraphic(textField);
textField.selectAll();
textField.requestFocus();
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem().getTyp());
setGraphic(null);
}
@Override
public void commitEdit(Typ person) {
super.commitEdit(person);
person.setTyp(textField.getText());
setText(textField.getText());
setGraphic(null);
}
});