【问题标题】:JavaFX making cellFactory genericJavaFX 使 cellFactory 通用
【发布时间】:2017-06-10 06:40:50
【问题描述】:

我正在尝试编写一种方法,该方法允许我为作为参数传递的特定列设置列工厂。在这种情况下,我有 Orders 和 Food,这两个类在某个时间点都显示在 TableView 中,并且都有一个我想格式化为价格的列。

这就是它的工作原理:

priceColumn.setCellFactory(col ->
            new TableCell<Food, Double>() {
                @Override
                public void updateItem(Double price, boolean empty) {
                    super.updateItem(price, empty);
                    if (empty) {
                        setText(null);
                    } else {
                        setText(String.format("%.2f €", price));
                    }
                }

            }
    );

这是我的 Formatting 类,我在其中尝试使其通用,而不是为每一列复制粘贴相同的东西。问题是它什么都不会显示。

public static <T> void priceCellFormatting(TableColumn tableColumn){
    System.out.println();
    tableColumn.setCellFactory(col ->
    new TableCell<T, Double>() {

        protected void updateItem(double item, boolean empty) {
            super.updateItem(item, empty);
            if(empty){
                setText(null);
            }else {
                setText(String.format("%.2f €", item));
            }


        }
    });

}

我调用这个方法,除了价格之外的每一列都被填满:

private void fillTableListView() {
        nameColumn.setCellValueFactory(new PropertyValueFactory<Order, String>("name"));
        amountColumn.setCellValueFactory(new PropertyValueFactory<Order, Integer>("amount"));
        priceColumn.setCellValueFactory(new PropertyValueFactory<Order, Double>("price"));
        totalColumn.setCellValueFactory(new PropertyValueFactory<Order, Double>("total"));

    Formatting.priceCellFormatting(priceColumn);
    try {
        orderTableView.setItems(OrderDAO.getOrder());
    } catch (SQLException e) {
        System.out.println("Exception at filling tablelistview: " + e);
    }
}

【问题讨论】:

标签: java generics javafx


【解决方案1】:

有一个小错字会对您的代码产生巨大影响。你用过

protected void updateItem(double item, boolean empty)

而不是

protected void updateItem(Double item, boolean empty)

由于您使用基本类型double 而不是也用作类型参数的Double 类型,因此您无需覆盖updateItem 方法,而是创建一个新方法。这种方法从未使用过。而是使用默认的updateItem 方法。此实现不会修改单元格的文本。

提示: 总是在覆盖方法时使用@Override 注释。这允许编译器检查这样的错误。此外,您可能还应该在 priceCellFormatting 方法中添加方法参数的类型参数:

public static <T> void priceCellFormatting(TableColumn<T, Double> tableColumn){
    System.out.println();

    tableColumn.setCellFactory(col ->
        new TableCell<T, Double>() {

            @Override
            protected void updateItem(Double item, boolean empty) {
                super.updateItem(item, empty);
                if(empty){
                    setText(null);
                }else {
                    setText(String.format("%.2f €", item));
                }


            }
        });

}

【讨论】:

  • 哇,看到这么小的错字真是救命啊。我真的认为这是因为我缺乏仿制药的经验。现在效果很好!
猜你喜欢
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-01
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
相关资源
最近更新 更多