如果字段输入为空,TableColumn 停止 EditCommit
TableColumn stop EditCommit if field-input is blank
我有这个TableColumn<Foo, String> colValue = new TableColumn<>("Value");
使用此设置:
colValue.setCellValueFactory(new PropertyValueFactory<>("value"));
colValue.setCellFactory(TextFieldTableCell.forTableColumn());
colValue.setOnEditCommit(event -> {
//get new value
String newValue = event.getNewValue().trim();
//if is empty not update
if(newValue.isEmpty()){ return; }
//set new value
event.getRowValue().setValue(newValue);
//refresh table
tableView.refresh();
});
我想要的是直接从table更新对象字段。双击单元格时,更改值并提交。
但是我不想在字段输入为空时更新值。
以上代码运行良好。它仅在值不为空时更新对象。
但是问题是,如果field-input是黑色的,并且有commit,对象没有更新,但是cell是空白的。
如何防止单元格提交?如果提交时字段输入为空,我想在单元格中查看旧值(对象的实际值)。
似乎在触发事件时,拦截更新单元格的文本为时已晚。
这有点 hack(可能更好的方法是直接继承 TableCell
并实现在用户点击回车等时直接调用 cancelEdit
的行为,使用空细绳)。但是,您可以按如下方式覆盖 commitEdit(...)
方法:
colValue.setCellValueFactory(new PropertyValueFactory<>("value"));
//colValue.setCellFactory(TextFieldTableCell.forTableColumn());
//colValue.setOnEditCommit(event -> {
//
// //get new value
// String newValue = event.getNewValue().trim();
//
// //if is empty not update
// if(newValue.isEmpty()){ return; }
//
// //set new value
// event.getRowValue().setValue(newValue);
//
// //refresh table
// tableView.refresh();
//
//});
colValue.setCellFactory(tc -> new TextFieldTableCell<>(TextFormatter.IDENTITY_STRING_CONVERTER) {
@Override
public void commitEdit(String newValue) {
if (newValue.isEmpty()) {
cancelEdit();
} else {
super.commitEdit(newValue);
}
}
});
我有这个TableColumn<Foo, String> colValue = new TableColumn<>("Value");
使用此设置:
colValue.setCellValueFactory(new PropertyValueFactory<>("value"));
colValue.setCellFactory(TextFieldTableCell.forTableColumn());
colValue.setOnEditCommit(event -> {
//get new value
String newValue = event.getNewValue().trim();
//if is empty not update
if(newValue.isEmpty()){ return; }
//set new value
event.getRowValue().setValue(newValue);
//refresh table
tableView.refresh();
});
我想要的是直接从table更新对象字段。双击单元格时,更改值并提交。
但是我不想在字段输入为空时更新值。
以上代码运行良好。它仅在值不为空时更新对象。
但是问题是,如果field-input是黑色的,并且有commit,对象没有更新,但是cell是空白的。
如何防止单元格提交?如果提交时字段输入为空,我想在单元格中查看旧值(对象的实际值)。
似乎在触发事件时,拦截更新单元格的文本为时已晚。
这有点 hack(可能更好的方法是直接继承 TableCell
并实现在用户点击回车等时直接调用 cancelEdit
的行为,使用空细绳)。但是,您可以按如下方式覆盖 commitEdit(...)
方法:
colValue.setCellValueFactory(new PropertyValueFactory<>("value"));
//colValue.setCellFactory(TextFieldTableCell.forTableColumn());
//colValue.setOnEditCommit(event -> {
//
// //get new value
// String newValue = event.getNewValue().trim();
//
// //if is empty not update
// if(newValue.isEmpty()){ return; }
//
// //set new value
// event.getRowValue().setValue(newValue);
//
// //refresh table
// tableView.refresh();
//
//});
colValue.setCellFactory(tc -> new TextFieldTableCell<>(TextFormatter.IDENTITY_STRING_CONVERTER) {
@Override
public void commitEdit(String newValue) {
if (newValue.isEmpty()) {
cancelEdit();
} else {
super.commitEdit(newValue);
}
}
});