FileDocCategorySizeDatePackage
TreeDropTarget.javaAPI DocExample2689Thu Oct 24 20:14:28 BST 2002None

TreeDropTarget

public class TreeDropTarget extends Object implements DropTargetListener

Fields Summary
DropTarget
target
JTree
targetTree
Constructors Summary
public TreeDropTarget(JTree tree)

    targetTree = tree;
    target = new DropTarget(targetTree, this);
  
Methods Summary
public voiddragEnter(java.awt.dnd.DropTargetDragEvent dtde)

    TreeNode node = getNodeForEvent(dtde);
    if (node.isLeaf()) {
      dtde.rejectDrag();
    }
    else {
      // start by supporting move operations
      //dtde.acceptDrag(DnDConstants.ACTION_MOVE);
      dtde.acceptDrag(dtde.getDropAction());
    }
  
public voiddragExit(java.awt.dnd.DropTargetEvent dte)

 
public voiddragOver(java.awt.dnd.DropTargetDragEvent dtde)

    TreeNode node = getNodeForEvent(dtde);
    if (node.isLeaf()) {
      dtde.rejectDrag();
    }
    else {
      // start by supporting move operations
      //dtde.acceptDrag(DnDConstants.ACTION_MOVE);
      dtde.acceptDrag(dtde.getDropAction());
    }
  
public voiddrop(java.awt.dnd.DropTargetDropEvent dtde)

    Point pt = dtde.getLocation();
    DropTargetContext dtc = dtde.getDropTargetContext();
    JTree tree = (JTree)dtc.getComponent();
    TreePath parentpath = tree.getClosestPathForLocation(pt.x, pt.y);
    DefaultMutableTreeNode parent = 
      (DefaultMutableTreeNode)parentpath.getLastPathComponent();
    if (parent.isLeaf()) {
      dtde.rejectDrop();
      return;
    }

    try {
      Transferable tr = dtde.getTransferable();
      DataFlavor[] flavors = tr.getTransferDataFlavors();
      for (int i = 0; i < flavors.length; i++) {
	if (tr.isDataFlavorSupported(flavors[i])) {
	  dtde.acceptDrop(dtde.getDropAction());
	  TreePath p = (TreePath)tr.getTransferData(flavors[i]);
	  DefaultMutableTreeNode node = 
	    (DefaultMutableTreeNode)p.getLastPathComponent();
	  DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
	  model.insertNodeInto(node, parent, 0);
	  dtde.dropComplete(true);
	  return;
	}
      }
      dtde.rejectDrop();
    } catch (Exception e) {
      e.printStackTrace();
      dtde.rejectDrop();
    }
  
public voiddropActionChanged(java.awt.dnd.DropTargetDragEvent dtde)

 
private javax.swing.tree.TreeNodegetNodeForEvent(java.awt.dnd.DropTargetDragEvent dtde)

    Point p = dtde.getLocation();
    DropTargetContext dtc = dtde.getDropTargetContext();
    JTree tree = (JTree)dtc.getComponent();
    TreePath path = tree.getClosestPathForLocation(p.x, p.y);
    return (TreeNode)path.getLastPathComponent();