Reputation:
I have a tree view that looks like this.
-Root
--Parent 1
----Child 1
----Child 2
----Child 3
--Parent 2
----Child 1
----Child 2
I've looked all over SO and Google but I can't find a proper way to move TreeItems up and down in the tree list. Is this possible?
I'm not talking about just moving the child
nodes, rather when I move the parents up, I need the children to move with them as well. So moving Parent 2
up would look like this.
-Root
--Parent 2
----Child 1
----Child 2
--Parent 1
----Child 1
----Child 2
----Child 3
Upvotes: 1
Views: 2612
Reputation: 13
public void moveDown() {
if (selectedItem != null) {
TreeItem item = selectedItem;
int index = item.getParent().getChildren().indexOf(item);
if(index != item.getParent().getChildren().size()-1)
{
TreeItem safeItem = (TreeItem) item.getParent().getChildren().get(index+1);
item.getParent().getChildren().set(index+1, item);
item.getParent().getChildren().set(index, safeItem);
}
}
}
Upvotes: 0
Reputation: 11134
I would suggest using a SortedList
instead of an ObservableList
as a backing list for your JavaFX TreeView
.
On the SortedList
there is a comparatorProperty
, whenever it changes, the List
gets reordered accordingly. Easy as pie ;-)
Upvotes: 4
Reputation: 1907
You have to move the TreeItem up in its parent childlist.
Run the following method on the node that shall move up:
static void moveUp(TreeItem item) {
if (item.getParent() instanceof TreeItem) {
TreeItem parent = item.getParent();
List<TreeItem> list = new ArrayList<TreeItem>();
Object prev = null;
for (Object child : parent.getChildren()) {
if (child == item) {
list.add((TreeItem)child);
} else {
if (prev != null) list.add((TreeItem)prev);
prev = child;
}
}
if (prev != null) list.add((TreeItem)prev);
parent.getChildren().clear();
parent.getChildren().addAll(list);
}
}
that is somehow ugly Java code, but works. Move down is similar.
The children will follow, as the TreeView redraws automatically
Upvotes: 2