【问题标题】:ListView unable to add and edit cell when emptyListView 为空时无法添加和编辑单元格
【发布时间】:2016-08-31 09:01:52
【问题描述】:

我正在尝试使用 ListView 作为字符串的编辑器,它来自自定义数据模型。我将TextFieldListCells 与适当的StringConverter 一起用于单元格。

ListView 旁边有一个添加按钮,它在操作时调用此方法:

@FXML
private void addElement() {
    WordListItem newItem = new WordListItem(-1, "");

    wordListItems.add(newItem);
    wordListView.setEditable(true);
    wordListView.getSelectionModel().select(wordListItems.indexOf(newItem));
    wordListView.edit(wordListItems.indexOf(newItem));
    wordListView.setEditable(false);
}

其中wordListViewListViewwordListItems 是包含wordListView 数据的ObservableList

这确实有效,除了列表为空(非空)时,我无法完全解释原因,因此我检查了 Java 源代码以寻求帮助。

到目前为止,我发现:edit(int) 调用 ListView 更改了 ListViews 内部 editIndex 值,它应该调用 EDIT_START EventeditIndexReadOnlyIntegerWrapper,我在其中发现了一些我不太理解的奇怪代码,我不确定这是否真的产生了错误,或者我只是看不出他们为什么这样做:

@Override
protected void fireValueChangedEvent() {
    super.fireValueChangedEvent();
    if (readOnlyProperty != null) {
        readOnlyProperty.fireValueChangedEvent();
    }
}

每当ListVieweditIndex 属性发生更改时,都会调用此方法。问题:readOnlyProperty 为空,因为它没有在任何地方设置。我能找到的唯一设置位置是在 getter 中:

public ReadOnlyIntegerProperty getReadOnlyProperty() {
    if (readOnlyProperty == null) {
        readOnlyProperty = new ReadOnlyPropertyImpl();
    }
    return readOnlyProperty;
}

ReadOnlyIntegerImpl 是一个内部私有类,readOnlyProperty 是它的类型)


现在是我的实际问题:这是一个错误还是我在监督什么?有什么原因我不能像这样在列表中添加和编辑新创建的元素,因为它是空的,还是真的只是这个 getter 还没有被调用?

【问题讨论】:

标签: java javafx javafx-8


【解决方案1】:

您找到的源代码只是延迟初始化属性的代码。

除非为属性分配新值或请求属性本身,否则null 可以用作属性以避免不必要地创建属性对象。这不是问题。

问题似乎是在调用edit 之前未更新ListView 单元格。这发生在布局期间,因此在开始编辑之前“手动”调用layout 应该可以工作:

private void addElement() {
    WordListItem newItem = new WordListItem(-1, "");

    wordListItems.add(newItem);
    wordListView.setEditable(true);

    wordListView.layout();

    wordListView.edit(wordListItems.size()-1);
    wordListView.setEditable(false);
}

【讨论】:

  • 谢谢。 wordListItems.size()-1 是有道理的,在我开始尝试调试之前就是这样。那条奇怪的线,选择正在编辑的线实际上是我发现的 actual 错误的一种解决方法。
猜你喜欢
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
相关资源
最近更新 更多