Phi*_*yyy 6 java listview javafx listener
我有两个ListViews,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);
}
});
Run Code Online (Sandbox Code Playgroud)
作为快速修复,您可以将修改项目列表的代码部分包装到一个Platform.runLater(...)块中:
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);
});
Run Code Online (Sandbox Code Playgroud)
问题是在处理选择更改时无法更改选择。当您删除带有 的所有元素时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);
});
}
});
Run Code Online (Sandbox Code Playgroud)
它将选定的索引设置为-1:在删除当前项目时不选择任何内容,以ListView避免更改为不同的项目(这是通过清除列表在您的版本中隐式完成的),然后将当前选定的元素添加到“选定的元素”中。 list”,然后它从“所有项目列表”中删除当前元素。所有这些操作都包含在提到的Platform.runLater(...)块中。
| 归档时间: |
|
| 查看次数: |
833 次 |
| 最近记录: |