When dropping an object over a JTree, how do you determine the node being dropped over?

John Zukowski

The importData() method of your TransferHandler has a TransferSupport argument. From this support object, you can ask for the drop location with getDropLocation(). This returns an implementation of TransferHandler.DropLocation, which for a JTree is a JTree.DropLocation. From the drop location, you can ask for the child index via getChildIndex() to identify the drop location, and add it to that location in the parent node. Here's what your importData() method might look like:

  public boolean importData(TransferHandler.TransferSupport support) {
    if (!canImport(support)) {
      return false;

    JTree.DropLocation dropLocation =

    TreePath path = dropLocation.getPath();

    Transferable transferable = support.getTransferable();

    String transferData;
    try {
      transferData = (String)transferable.getTransferData(
    } catch (IOException e) {
      return false;
    } catch (UnsupportedFlavorException e) {
      return false;

    int childIndex = dropLocation.getChildIndex();
    if (childIndex == -1) {
      childIndex = model.getChildCount(path.getLastPathComponent());

    DefaultMutableTreeNode newNode =
      new DefaultMutableTreeNode(transferData);
    DefaultMutableTreeNode parentNode =
    model.insertNodeInto(newNode, parentNode, childIndex);

    TreePath newPath = path.pathByAddingChild(newNode);

    return true;