简体   繁体   English

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

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

I'm trying to build a program in JavaFX that allows me to check a list of payments in a TableView. 我正在尝试使用JavaFX构建程序,该程序允许我检查TableView中的付款列表。 To do this I created a class Bill that contains all the data I need, and in particular the attribute amount. 为此,我创建了一个Bill类,其中包含我需要的所有数据,尤其是属性数量。 The amount could be an exit or an entry, and this is estabilished by the enum Type in Bill (that can be ENTRY or EXIT). 金额可以是退出或输入,这由Bill中的枚举类型(可以是ENTRY或EXIT)确定。 Now, I'm trying to override the method updateItem of TableCell to set the background color of the amount column green if the amount is an entry or red if it's an exit. 现在,我试图覆盖TableCell的updateItem方法,以将金额列的背景色设置为绿色(如果该金额是输入项)或红色(如果其是退出项)。

This is my code for the class AmountCell that extends TableCell and overrides 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" ));
    }
}
}

The problem is that when the records are displayed in the TableView, also the last empty rows of the table are colored, and I can't understand why! 问题是,当记录显示​​在TableView中时,表的最后空行也会被着色,而我不明白为什么! Also, try to debug the program, I noticed that the method updateItem has a strange behavior: it's often called twice with nosense. 另外,尝试调试程序,我注意到方法updateItem有一个奇怪的行为:它经常被无礼地调用两次。 Anyone can explain me why and when the method is effectively called? 任何人都可以向我解释为什么以及何时有效调用该方法?

updateItem is called when TableView determines the cell value has changed. TableView确定单元格值已更改时,将调用updateItem Since cells are reused, 由于单元被重用,

  • Different items may be assigned to the same cell during it's lifecycle 生命周期中可能会将不同的项目分配给同一单元
  • cells that contained an item could become empty again (for this reason you should make sure to deal with the case of the cell becoming empty by reseting to the "empty" state.) 包含项目的单元格可能会再次变空(因此,您应确保通过重置为“空”状态来处理单元格变空的情况。)

In this case you need to clear the style when the item becomes null . 在这种情况下,您需要在该项变为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" ));
    }
}

Note: For currency it's better to use BigDecimal to avoid rounding issues. 注意:对于货币,最好使用BigDecimal以避免舍入问题。

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

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