【发布时间】:2018-07-27 07:16:38
【问题描述】:
所以我的应用程序使用不同 FXMLViewController 中的多个 TableView 来呈现多个不同的 JPA 实体。以下示例适用于 JobSupplierParts。
/**
* renderDoubleColumn takes a TableColumn setting its value and type before setting up edit event handling.
* @param column the tableColumn to be set up.
* @param field the name of the field to be mapped to.
* @param methodName the set method name of the field.
*/
protected void renderDoubleColumn(TableColumn<JobSupplierPart, Double> column, String field, String methodName) {
String className = "BiasDB.JobSupplierPart";
column.setCellValueFactory(new PropertyValueFactory<>(field));
column.setCellFactory(TextFieldTableCell.<JobSupplierPart, Double>forTableColumn(new DoubleStringConverter()));
column.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<JobSupplierPart, Double>>() {
@Override
public void handle(TableColumn.CellEditEvent<JobSupplierPart, Double> t) {
JobSupplierPart supplierPart = t.getTableView().getItems().get(t.getTablePosition().getRow());
try {
Class<?> c = Class.forName(className);
Method method = c.getDeclaredMethod(methodName, Double.class);
method.invoke(supplierPart, t.getNewValue());
supplierPart.setTotal(updateItem(supplierPart));
} catch (ClassNotFoundException|NoSuchMethodException|IllegalAccessException|InvocationTargetException ex) {
logger.error("renderDoubleColumn",ex);
} //End try to get method from String.
try {
jobSupplierPartController.edit(supplierPart);
} catch (Exception ex) {
logger.error("renderDoubleColumn",ex);
}
t.getTableView().refresh();
}
} //END Event Handler
); //END SetOnEditCommit.
}
//END renderDoubleColumn
我可以这样称呼它:
renderDoubleColumn(discountColumn, "discount", "setDiscount");
但是 - 我必须为每个 JPA 实体创建新方法。是否可以替换对 JobSupplierPart 的引用,使其成为一种通用方法,就像我用这些方法实现的一样?我已经尝试过 T 或 K 等替代方案,但它们都返回了错误。控制器只能作为参数传递。或者这是一个非常糟糕的做法/性能不佳的事情?
【问题讨论】:
-
那是糟糕的代码(在非常正常的上下文中使用反射,调用 table.refresh) - 为什么你觉得必须与 fx 作斗争?
-
@kleopatra。你想扩大。我很想学习。在进入 Python 和 PHP 13 年后才回到 Java。您为什么不遵循 DRY 原则并拥有一个方法,而不是许多相同的方法,但只需更改一些名称。
-
@kleopatra。嗨,我不知道您是否会觉得我现在发布的答案不那么糟糕了 - 我希望如此!