Example usage for javax.swing JTree getClosestPathForLocation

List of usage examples for javax.swing JTree getClosestPathForLocation

Introduction

In this page you can find the example usage for javax.swing JTree getClosestPathForLocation.

Prototype

public TreePath getClosestPathForLocation(int x, int y) 

Source Link

Document

Returns the path to the node that is closest to x,y.

Usage

From source file:TreeDragTest.java

private TreeNode getNodeForEvent(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();
}

From source file:TreeDragTest.java

public void drop(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();/*ww  w .j a  v a2s . c  o  m*/
        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();
    }
}