编辑TextFieldListCell时,会显示相应的类

时间:2014-12-12 10:15:17

标签: java listview javafx

我有以下代码用于编辑ListView中的单元格:

listView.setCellFactory(new Callback<ListView<TextModule>, ListCell<TextModule>>() {
  @Override public ListCell<TextModule> call(ListView<TextModule> param) {
    TextFieldListCell<TextModule> textCell = new TextFieldListCell<TextModule>() {
      @Override public void updateItem(TextModule item, boolean empty) {
        super.updateItem(item, empty);
        if (item != null) {
          setText( item.getSummary());
        }
        else {
          setText(null);
        }
      }
    };
    return textCell;
  }
});

现在的问题是,如果我通过双击在ListView内输入任何单元格,我可以编辑单元格,但属性(显示的文本)会更改为类{{1 }}。通常它会显示“Hello World”等文本。

1 个答案:

答案 0 :(得分:2)

如果您没有为TextFieldListCell提供正确的字符串转换器,它将使用默认实现(来自CellUtils):

private static <T> String getItemText(Cell<T> cell, StringConverter<T> converter) {
    return cell.getItem().toString();
}

在您的案例com.test.tools.tbm.model.TextModule@179326d中显示,cell.getItem()会返回TextModule的实例。

因此,您需要覆盖toString()课程中的TextModule

class TextModule {
    private final String summary;

    public TextModule(String summary){
        this.summary=summary;
    }

    public String getSummary(){ return summary; }

    @Override
    public String toString(){
        return summary;
    }
}

或者您可以提供自己的StringConverter

    listView.setCellFactory(TextFieldListCell.forListView(new StringConverter<TextModule>(){

        @Override
        public String toString(TextModule item) {
            return item.getSummary();
        }

        @Override
        public TextModule fromString(String string) {
            return new TextModule(string);
        }

    }));