我正在尝试在JavaFX中构建一个程序,它允许我检查TableView中的付款列表。为此,我创建了一个类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有一个奇怪的行为:它通常用nosense调用两次。任何人都可以解释为什么以及何时有效地调用该方法?
当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
来避免舍入问题。