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 =
      (JTree.DropLocation)support.getDropLocation();

    TreePath path = dropLocation.getPath();

    Transferable transferable = support.getTransferable();

    String transferData;
    try {
      transferData = (String)transferable.getTransferData(
        DataFlavor.stringFlavor);
    } 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 =
      (DefaultMutableTreeNode)path.getLastPathComponent();
    model.insertNodeInto(newNode, parentNode, childIndex);

    TreePath newPath = path.pathByAddingChild(newNode);
    tree.makeVisible(newPath);
    tree.scrollRectToVisible(tree.getPathBounds(newPath));

    return true;
  }
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact