尝试在按钮按下时将字符串添加到 ListView。

huangapple go评论77阅读模式
英文:

Trying to add string to ListView on button press

问题

我正在尝试在按钮按下时将字符串添加到我的ListView,但它没有被添加。我猜想问题可能出在刷新ListView上,但我不知道怎么做。

英文:

I am trying to add the string to my ListView on a button press, but it isn't adding it. I'm assuming the issue is with refreshing the ListView, but I don't know exactly how to do that.

答案1

得分: 1

FXCollections.observableArrayList(...) 创建一个新的可观察列表并将提供的元素添加到其中。如果您在这里传递一个数组,数组的元素将被复制到新列表中,数组与可观察列表之间将不再有任何连接,因此数组的后续更改不会反映在可观察列表中。

您只需要直接更改后备列表。从您的代码中并不清楚您的意图:您的数组中有一个元素,并且您遍历数组(仅一次)将所有元素(仅有一个元素)更改为"k"

因此,等效于此操作,但修改列表的操作将如下所示:

addButton.setOnAction(e -> {
    lv.getItems().set(0, "k");
});

您问题的标题表示您想要向列表视图中添加一个元素,您可以使用以下代码实现:

addButton.setOnAction(e -> {
    lv.getItems().add("k");
});
英文:

FXCollections.observableArrayList(...) creates a new observable list and adds the elements provided to it. If you pass an array here, the elements of the array will be copied to the new list, and there will no longer be any connection between the array and the observable list, so subsequent changes to the array will not be reflected in the observable list.

All you need to do here is change the backing list directly. It's not really clear from your code what you intend to do: your array has one element in it, and you iterate through the array (i.e. just once) changing all the elements (there's only one) to "k".

So the equivalent of this, but modifying the list, would just be

addButton.setOnAction(e-> {
    lv.getItems().set(0, "k");
});

The title of your question says you want to add and element to the list view, which you would do with

addButton.setOnAction(e-> {
    lv.getItems().add("k");
});

huangapple
  • 本文由 发表于 2020年4月6日 08:25:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/61051252.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定