Java Swing: Drag and Drop in a Tree Control

I recently added Drag & Drop support to a tree control in one of my Java Swing apps. Sun's Java tutorials didn't discuss exactly what I needed to do, and much of the discussion on internet groups was misleading, so I forged ahead on my own. Here I hope to present it in the simplest possible terms.

To support Drag & Drop I did 3 things:

  • Turn it on: call 3 methods on the Tree supporing DnD:
    JTree.setDragEnabled(true)
    JTree.setDropMode(DropMode.INSERT)
    JTree.setTransferHandler(myHandler)
  • Create my own "handler" class that extends javax.swing.TransferHandler.
    This class is registered into the tree via JTree.setTransferHandler().
    During drag/drop operations, it is called repeatedly by the Java SDK.
  • Create my own class that implements java.awt.datatransfer.Transferable
    This class wraps the items being dragged (nodes of the TreeModel).
  • My tree uses a custom tree model which is the underlying data structure - not a wrapper. That data structure is a simple Composite design pattern: an Item, which has a (possibly empty) list of child Items. This naturally represents itself as a tree.

    My tree is a component of a JPanel (subclass of JPanel). The panel class members itsTree and itsTModel are the JTree and the tree's model. The TransferHandler class is defined inside the panel class.

    That should be enough explanation to understand the code:

    TransferHandler.java

    NOTE: this code is functional but will not compile as-is. It is a code snippet that is part of the JPanel subclass. Why? Because this covers 99% of everything you must do to support drag and drop. The rest of the Panel class has nothing to do with Drag and Drop so it would not help to include it.