我有两个ListView
s, allStudentsList
其中已经填充了项目,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(...)
块将通过“推迟”修改来阻止。
但是你的整个处理程序可以与
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
为了避免在删除当前项目时更改为不同的项目(这是通过清除列表在您的版本中隐式完成的),然后它将当前选定的元素添加到“选定列表”中,然后从“所有项目列表”。所有这些操作都包含在提到的内容中Platform.runLater(...)
block.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)