经过挖掘,我发现了如何获取列的属性名称。有了这个,我继续写了一些通用的反射来强制更新。为了便于使用,我将所有内容都包装在 commit(Object val) 方法中。这些是对使用here 的EditCell 类的修改。
免责声明:这仅在您使用 PropertyValueFactory 并遵循行类中的命名约定时才有效。这也是非常善变的代码,使用和修改请自行斟酌。
我将单元格修改为带有public static class EditingCell<S, T> extends TableCell<S, T> 的通用单元格。教程中的其他所有内容都应该保持不变,如果不能随时告诉我,我会在此处进行相应更新。
public void commit(Object val) {
// Get the table
TableView<S> t = this.getTableView();
// Get the selected row/column
S selectedRow = t.getItems().get(this.getTableRow().getIndex());
TableColumn<S, ?> selectedColumn = t.getColumns().get(t.getColumns().indexOf(this.getTableColumn()));
// Get current property name
String propertyName = ((PropertyValueFactory) selectedColumn.getCellValueFactory()).getProperty();
// Create a method name conforming to java standards ( setProperty )
propertyName = ("" + propertyName.charAt(0)).toUpperCase() + propertyName.substring(1);
// Try to run the update
try {
// Type specific checks - could be done inside each setProperty() method
if(val instanceof Double) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, double.class);
method.invoke(selectedRow, (double) val);
}
if(val instanceof String) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, String.class);
method.invoke(selectedRow, (String) val);
}
if(val instanceof Integer) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, int.class);
method.invoke(selectedRow, (int) val);
}
} catch (Exception e) {
e.printStackTrace();
}
// CommitEdit for good luck
commitEdit((T) val);
}
然后由于文本字段不会更新,我在cancelEdit() 中强制对其进行更新。这有点特定于我的情况(我想要默认值 0.0,并且只接受双精度值) - 根据需要进行修改。
@Override
public void cancelEdit() {
super.cancelEdit();
// Default value
String val = "0.0";
// Check to see if there's a value
if (!textField.getText().equals(""))
val = textField.getText();
// Set table cell text
setText("" + val);
setGraphic(null);
}