简体   繁体   中英

JavaFX - move TreeItem up down in TreeView

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

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 ;-)

You have to move the TreeItem up in its parent childlist.

  1. If you use a view-controller-model setup, do the reordering in the model, the tree shall update accordingly
  2. If you only want the view to change and not the model use a reordering in the getChildren() method of the own TreeItem implementation
  3. If your view also represents the model (data itself), then you might use the code below.

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

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);
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM