gpt4 book ai didi

java - 如何使用更改监听器 JavaFX 在两个 ListView 之间移动项目

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:24:24 24 4
gpt4 key购买 nike

我有两个 ListViewallStudentsList 中已经填充了项目,currentStudentList 没有。当用户在 allStudentList 中选择一个项目时,我的目标是将该项目移动到 currentStudentList 中。我通过在 allStudentList 的选择模型上放置一个监听器来完成此操作。

我得到一个 IndexOutOfBoundsException 并且我不确定为什么会发生这种情况。从测试来看,这个问题似乎与此方法的最后 4 行无关,但我不确定为什么。

allStudentsList.getSelectionModel().selectedItemProperty()
.addListener((observableValue, oldValue, newValue) -> {
if (allStudentsList.getSelectionModel().getSelectedItem() != null) {

ArrayList<String> tempCurrent = new ArrayList<>();
for (String s : currentStudentList.getItems()) {
tempCurrent.add(s);
}

ArrayList<String> tempAll = new ArrayList<>();
for (String s : allStudentsList.getItems()) {
tempAll.add(s);
}

tempAll.remove(newValue);
tempCurrent.add(newValue);

// clears current studentlist and adds the new list
if (currentStudentList.getItems().size() != 0) {
currentStudentList.getItems().clear();
}
currentStudentList.getItems().addAll(tempCurrent);

// clears the allStudentList and adds the new list
if (allStudentsList.getItems().size() != 0) {
allStudentsList.getItems().clear();
}
allStudentsList.getItems().addAll(tempAll);
}
});

最佳答案

作为快速修复,您可以将修改项目列表的代码部分包装到 Platform.runLater(...) block 中:

Platform.runLater(() -> {
// clears current studentlist and adds the new list
if (currentStudentList.getItems().size() != 0)
currentStudentList.getItems().clear();

currentStudentList.getItems().addAll(tempCurrent);
});

Platform.runLater(() -> {
// clears the allStudentList and adds the new list
if (allStudentsList.getItems().size() != 0)
allStudentsList.getItems().clear();

allStudentsList.getItems().addAll(tempAll);
});

问题是您无法在处理选择更改时更改选择。当您使用 allStudentsList.getItems().clear(); 删除所有元素时,选择将更改(所选索引将为 -1),将满足上述条件.这就是使用 Platform.runLater(...) block 将通过“推迟”修改来防止的情况。

但是你的整个处理程序可以交换

allStudentsList.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
if (newValue != null) {

Platform.runLater(() -> {
allStudentsList.getSelectionModel().select(-1);
currentStudentList.getItems().add(newValue);
allStudentsList.getItems().remove(newValue);
});
}
});

它将选定的索引设置为 -1:在 ListView 中没有选择任何内容,以避免在删除当前项目时更改为不同的项目(这是隐式完成的您的版本通过清除列表),然后它将当前选定的元素添加到 s“选定列表”,然后从“所有项目列表”中删除当前元素。所有这些操作都包含在提到的 Platform.runLater(...) block 中。

关于java - 如何使用更改监听器 JavaFX 在两个 ListView 之间移动项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39714874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com