【问题标题】:Generic Methods for Rendering TableColumns in JavaFX在 JavaFX 中呈现 TableColumns 的通用方法
【发布时间】: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。嗨,我不知道您是否会觉得我现在发布的答案不那么糟糕了 - 我希望如此!

标签: java javafx tableview


【解决方案1】:

因此,我不知道 Java 爱好者是否会同意此解决方案,但在我能够使代码更清晰后不久,我会响应发布的答案然后将其删除。我还将设置/编辑部分移到了一个方法中,所以现在我有了:

/**
 * renderBigDecimalColumn 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.
 */
private void renderBigDecimalColumn(TableColumn<AccountAsset, BigDecimal> column, String field) {

    //Set an observable value for the column
    column.setCellValueFactory(new PropertyValueFactory<>(field));

    //Set how we want the cell to be rendered
    // This line varies for the different cell types e.g. Strings, Bools etc.
    column.setCellFactory(TextFieldTableCell.<AccountAsset, BigDecimal>forTableColumn(new BigDecimalStringConverter()));

    //Set how we want the cell to be edited including the row update.
    column.setOnEditCommit(t -> {
        handleEditCommit(t, field);
    }); //END SetOnEditCommit.

} //END renderBigDecimalColumn

我的 handleEditCommit 方法看起来像:

/** handleEditCommit deals with updating and saving the new data from the table view.
 *
 * @param t
 * @param field
 */
private void handleEditCommit(javafx.scene.control.TableColumn.CellEditEvent<AccountAsset,?> t, String field) {
    AccountAsset rowData = t.getTableView().getItems().get(t.getTablePosition().getRow());

    //Set the new value.
    try {
        BeanUtils.setProperty(rowData, field, t.getNewValue());
    } catch (IllegalAccessException | InvocationTargetException ex) {
        logger.error("handleEditCommit / Setter", ex);
    }

    //Save the new rowData back to the database.
    try {
        tableDataController.edit(rowData);
    } catch (Exception ex) {
        logger.error("handleEditCommit / Edit", ex);
    }
}

【讨论】:

  • 从 Java 8 开始,您可以使用方法引用,它比基于字符串的字段名称更不容易出错,并提供编译时检查(针对类型、名称、访问等)。使用Callback 或Function 作为getter,使用BiConsumer 作为setter,并通过例如AccountAsset::getDiscount 和 AccountAsset::setDiscount ... 如果你有 FX 风格的属性,你可以传递属性 getter。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 2019-02-05
  • 2015-05-21
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多