我正在尝试使用JavaFX构建程序,该程序允许我检查TableView中的付款列表。为此,我创建了一个Bill类,其中包含我需要的所有数据,尤其是属性数量。金额可以是退出或输入,这由Bill中的枚举类型(可以是ENTRY或EXIT)确定。 现在,我试图覆盖TableCell的updateItem方法,以将金额列为背景(如果金额为条目)设置为绿色,如果金额为退出则为红色。
这是我的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中时,表的最后空行也会被着色,而我不明白为什么!另外,尝试调试程序,我注意到方法updateItem有一个奇怪的行为:它经常被无礼地调用两次。任何人都可以向我解释为什么以及何时有效调用该方法?
答案 0 :(得分:0)
updateItem
确定单元格值已更改时,将调用 TableView
。由于单元已被重复使用,
在这种情况下,您需要在商品变为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
以避免舍入问题。