javafx中的listview.cellFacoty方法中为什么会调用super.updateItem(item, empty)?

Mau*_*tel 3 java javafx javafx-2 javafx-8

代码:

mpcListView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
    @Override
    public ListCell<String> call(ListView<String> param){
        return new XCell();
    }
});

public class XCell extends ListCell<String>{
    HBox hbox = new HBox();
    Label label = new Label();
    Button button = new Button("",getImage());
    String lastItem;

    public XCell(){
        super();
        hbox.setSpacing(120);
        hbox.getChildren().addAll(label,button);
        button.setOnAction(new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent event){
                mpcListView.getItems().remove(lastItem);
            }
        });
    }

    @Override
    protected void updateItem(String item, boolean empty){
        super.updateItem(item, empty);
        if (empty){
            lastItem = null;
            setGraphic(null);
        }else{
            lastItem = item;
            label.setText(item);
            setGraphic(hbox);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么super.updateItem(item, empty)叫?

zen*_*eni 5

ListCell updateItem(...) 实现非常重要,因为它调用 Cell updateItem(...) 实现来检查它是否为空并调用正确的方法:setItem(...) 或 setEmpty(...)。

如果你不调用 super.updateItem(...) 那么 Cell.updateItem(...) 不会被调用并且 setItem(...) 不会被调用然后......没有绘制任何内容或值没有更新!ListCell 只是在使用 Cell updateItem 实现之前添加了一些检查,因此您有两个选择:

  • 您可以在自定义 ListCell 实现中调用 super.updateItem(...)
  • 您可以在 updateItem 实现中调用 setItem(...) 和 setEmpty(...) 并在检查和编辑内容时“绕过” ListCell 实现

请注意, ListCell 它不是 ListView 使用的“基本”实现。请参考 TextFieldListCell 类,它是它实际工作方式的一个很好的例子,从 mercurial 获取源并阅读,它始终是最好的方法。

例如,TextFieldListCell 使用 super.updateItem(...) 调用 Cell.updateItem 实现来检查它是否为空(通过使用 setItem 或 setEmpty),然后使用 javafx.scene.control.cell.CellUtils.updateItem(. ...)。此方法获取在当前单元格中设置的项目,然后使用项目上的转换器在标签中显示字符串。