JavaFX TreeView Drag & Drop

JavaFX’s TreeView is a powerful component, but the code required to implement some of the finer details is not necessarily obvious.

drag-dropThe ability to rearrange tree nodes via drag and drop is a feature that users typically expect in a tree component.  A drag image and a drop location hint should also be employed to enhance usability.  In this post, we’ll explore an example that handles all of these things.

Note to Swing Developers

TreeView is fundamentally different from Swing’s JTree.   While JTree’s cell renderer uses a single component to “rubber stamp” each cell, TreeView’s cells are actual components.  TreeView creates enough cells to satisfy the needs of viewport, and these cells scan be reused as the user scrolls and interacts with the tree.  This approach allows custom cells to be interactive; for example, a cell may contain a clickable button or other component.  Facilitating this type of interaction with JTree required some hackery since the cell was only a “picture” of the actual component.

Creating a TreeView

Creating a TreeView is straightforward.  For the sake of this example, I’ve simply hard coded a few nodes.

TreeItem rootItem = new TreeItem(new TaskNode("Tasks"));

ObservableList children = rootItem.getChildren();
children.add(new TreeItem(new TaskNode("do laundry")));
children.add(new TreeItem(new TaskNode("get groceries")));
children.add(new TreeItem(new TaskNode("drink beer")));
children.add(new TreeItem(new TaskNode("defrag hard drive")));
children.add(new TreeItem(new TaskNode("walk dog")));
children.add(new TreeItem(new TaskNode("buy beer")));

TreeView tree = new TreeView(rootItem);
tree.setCellFactory(new TaskCellFactory());

Creating Cells

The cell factory is more interesting. With JTree, drag and drop was registered at the tree level.  With TreeView, the individual cells participate directly.  Drag event handlers must be set for each cell that is created:

cell.setOnDragDetected((MouseEvent event) -> dragDetected(event, cell, treeView));
cell.setOnDragOver((DragEvent event) -> dragOver(event, cell, treeView));
cell.setOnDragDropped((DragEvent event) -> drop(event, cell, treeView));
cell.setOnDragDone((DragEvent event) -> clearDropLocation());

Drag Detected

Inside dragDetected(), we must decide whether a node is actually draggable. If it is, the underlying value is added to the clipboard content.

private void dragDetected(MouseEvent event, TreeCell treeCell, TreeView treeView) {
    draggedItem = treeCell.getTreeItem();

    // root can't be dragged
    if (draggedItem.getParent() == null) return;
    Dragboard db = treeCell.startDragAndDrop(TransferMode.MOVE);

    ClipboardContent content = new ClipboardContent();
    content.put(JAVA_FORMAT, draggedItem.getValue());
    db.setDragView(treeCell.snapshot(null, null));

Drag Over

Our dragOver() method is triggered when the user is dragging a node over the cell. In this method we must decide whether the node being dragged could be dropped in this location, and if so, set a style on this cell that yields a visual hint as to where the dragged node will be placed if dropped.

private void dragOver(DragEvent event, TreeCell treeCell, TreeView treeView) {
    if (!event.getDragboard().hasContent(JAVA_FORMAT)) return;
    TreeItem thisItem = treeCell.getTreeItem();

    // can't drop on itself
    if (draggedItem == null || thisItem == null || thisItem == draggedItem) return;
    // ignore if this is the root
    if (draggedItem.getParent() == null) {

    if (!Objects.equals(dropZone, treeCell)) {
        this.dropZone = treeCell;

Drag Dropped

If a node is actually dropped, the drop() method handles removing the dropped node from the old location and adding it to the new location.

private void drop(DragEvent event, TreeCell treeCell, TreeView treeView) {
    Dragboard db = event.getDragboard();
    boolean success = false;
    if (!db.hasContent(JAVA_FORMAT)) return;

    TreeItem thisItem = treeCell.getTreeItem();
    TreeItem droppedItemParent = draggedItem.getParent();

    // remove from previous location

    // dropping on parent node makes it the first child
    if (Objects.equals(droppedItemParent, thisItem)) {
        thisItem.getChildren().add(0, draggedItem);
    else {
        // add to new location
        int indexInParent = thisItem.getParent().getChildren().indexOf(thisItem);
        thisItem.getParent().getChildren().add(indexInParent + 1, draggedItem);


TreeItem is not serializable, so it cannot be placed on the clipboard when a drag is recognized. Instead, the value object behind the TreeItem is the more likely candidate for the clipboard. This is unfortunate, however, because downstream drag/drop event methods need to know the TreeItem that is being dragged and it would be convenient if it were on the clipboard. We have a couple of choices- store the dragged item in a variable (the approach taken in this example), or search the tree looking for the TreeItem that corresponds to the value object on the clipboard.


Adding D&D-based reordering to a TreeView isn’t difficult once you have the pattern to follow! Find the entire source of this example here.

3 thoughts on “JavaFX TreeView Drag & Drop

  1. Thank you, i just tried this and drag and drop worked well.
    But when i clicked “Task” the treeview`s collapse function did not work well.
    I worked just changing arrow, not collapse under items.
    How can i do that?


    1. Hello, Just put this in your code.

      protected void updateItem(NodeXmlConfiguracao item, boolean empty) {
      super.updateItem(item, empty);
      // Clean Style, Graphic, and Text after collapse or remove one node.
      if (item == null) {



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s