为什么 TableCell 的方法 updateItem() 在 JavaFX 中没有正确的行为?

Why doesn't TableCell's method updateItem() have the correct behaviour in JavaFX?

我正在尝试用 JavaFX 构建一个程序,允许我在 TableView 中检查付款列表。为此,我创建了一个 class 账单,其中包含我需要的所有数据,尤其是属性金额。金额可以是退出或进入,这是由 Bill 中的枚举类型(可以是 ENTRY 或 EXIT)确定的。 现在,我试图覆盖 TableCell 的 updateItem 方法,以将金额列的背景颜色设置为绿色(如果金额是入口)或红色(如果是出口)。

这是我的 class AmountCell 代码,它扩展了 TableCell 并覆盖了 updateItem:

public class AmountCell extends TableCell<Bill, Float> {

@Override
protected void updateItem(Float item, boolean empty) {
    super.updateItem(item, empty);

    setText(item==null ? "" : String.format("%.2f", item.floatValue()));

    if(item != null) {
        setStyle("-fx-background-color: " + (getTableRow().getItem().getType() == Type.ENTRY ? "#93C572" : "#CC0000" ));
    }
}
}

问题是在TableView中显示记录时,table的最后一个空行也是彩色的,我不明白为什么!另外,尝试调试程序,我注意到 updateItem 方法有一个奇怪的行为:它经常被毫无意义地调用两次。任何人都可以解释为什么以及何时有效调用该方法?

updateItemTableView 确定单元格值已更改时调用。由于细胞被重复使用,

  • 在同一个单元格的生命周期中,可能会分配不同的项目
  • 包含项目的单元格可能会再次变空(因此,您应该确保通过重置为 "empty" 状态来处理单元格变空的情况。)

在这种情况下,您需要在项目变为 null 时清除样式。

@Override
protected void updateItem(Float item, boolean empty) {
    super.updateItem(item, empty);

    setText(item == null ? "" : String.format("%.2f", item.floatValue()));

    if(item == null) {
        setStyle(null);
    } else {
        setStyle("-fx-background-color: " + (getTableRow().getItem().getType() == Type.ENTRY ? "#93C572" : "#CC0000" ));
    }
}

注意:对于货币,最好使用BigDecimal以避免舍入问题。