I have created a custom DefaultMutableTreeNode.Now I want to perform Drag and drop on the tree it is working fine but I want to remove the node after being dropped. But the thing is I can insert node into model but can't remove from model.
public class ORDnd extends TransferHandler {
ObjectNode sourceNode;
ObjectNode destinationParent;
@Override
public int getSourceActions(JComponent c) {
return MOVE;
}
@Override
protected Transferable createTransferable(JComponent source) {
return new TransferableNode((ObjectNode) ((JTree) source).getSelectionPath().getLastPathComponent(), DataFlavors.ORDataFlavor);
}
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
if (!support.isDrop()) {
return false;
}
try {
if (support.isDataFlavorSupported(DataFlavors.ORDataFlavor)) {
sourceNode = (ObjectNode) support.getTransferable().getTransferData(DataFlavors.ORDataFlavor);
} else {
return false;
}
} catch (UnsupportedFlavorException | IOException ex) {
Logger.getLogger(ReusableDnd.class.getName()).log(Level.SEVERE, null, ex);
}
JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
TreePath path = dropLocation.getPath();
if (path == null) {
return false;
}
destinationParent = (ObjectNode) path.getLastPathComponent();
return (destinationParent.isRoot() && sourceNode.isPage()) || (destinationParent.isPage() && sourceNode.isObject());
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (!canImport(support)) {
return false;
}
JTree tree = (JTree) support.getComponent();
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
if (destinationParent.getNode(sourceNode.getText()) == null) {
/** if (support.getSourceDropActions() == MOVE) {
model.removeNodeFromParent(sourceNode);//Not removing the node from the model
} **/
if (support.isDrop() && support.getDropAction() == MOVE)
{
model.removeNodeFromParent(sourceNode);//Working bcoz changed getSourceDropActions to getDropAction
}
model.insertNodeInto(sourceNode, destinationParent, destinationParent.getChildCount());//this is working fine
model.reload(sourceNode);
return true;
}
return false;
}
}
The thing is I forgot to add exportDone.Now it is working perfectly
@Override
protected void exportDone(JComponent source, Transferable data, int action) {
if (action != MOVE) {
return;
}
DefaultTreeModel model = (DefaultTreeModel) ((JTree) source).getModel();
try {
model.removeNodeFromParent((ObjectNode) data.getTransferData(DataFlavors.ORDataFlavor));
} catch (UnsupportedFlavorException | IOException ex) {
Logger.getLogger(ORDnd.class.getName()).log(Level.SEVERE, null, ex);
}
}