繁体   English   中英

JavaFX使cellFactory变得通用

[英]JavaFX making cellFactory generic

我正在尝试编写一个方法,允许我为作为参数传递的特定列设置列工厂。 在这个上下文中,我有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));
                    }
                }

            }
    );

这是我的格式化类,其中我试图使这个泛型而不是复制粘贴每列的相同的​​东西。 问题是它不会显示任何东西。

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);
    }
}

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

protected void updateItem(double item, boolean empty)

代替

protected void updateItem(Double item, boolean empty)

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

提示:重写方法时始终使用@Override注释。 这允许编译器检查这样的错误。 您还应该在priceCellFormatting方法中添加method参数的类型参数:

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));
                }


            }
        });

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM