我不想在拖放之后重新排序ListView
中的项目。它看起来并不像实际那样容易实现。是否有任何有效的最佳实践重新排序项目,帮助程序类或库...或者javafx可能有辅助方法?
答案 0 :(得分:0)
这是我刚才为这个问题写的解决方案。我确信有一个更快/更有效的解决方案,但这对我有用。参数具有以下含义:
dropIndex
:删除/移动项目的索引。listView
:当前ListView
以下是代码:
// save current selection temporarily
int[] indices = new int[listView.getSelectionModel().getSelectedIndices().size()];
int j = 0;
for (Integer i : listView.getSelectionModel().getSelectedIndices()) {
indices[j] = i;
++j;
}
// add items
listView.getItems().addAll(dropIndex, listView.getSelectionModel().getSelectedItems());
// clear selection
listView.getSelectionModel().clearSelection();
// change indices to remove items
int amountSmallerDropIndex = 0;
for (int i = 0; i < indices.length; i++) {
if (indices[i] >= dropIndex) {
indices[i] = indices[i] + indices.length;
} else {
amountSmallerDropIndex++;
}
}
// remove items
for (int i = indices.length - 1; i >= 0; i--) {
listView.getItems().remove(indices[i]);
}
// select moved items
listView.getSelectionModel().selectRange(dropIndex - amountSmallerDropIndex, dropIndex - amountSmallerDropIndex + indices.length);