ClassCastException while Drag and Drop in a JTree

159 views Asked by At

I want to make drag and drop in JTree. I follow this tutorial:

http://www.java2s.com/Code/Java/Swing-JFC/DnDdraganddropJTreecode.htm

Unfortunately I have in JTree nodes with my own class and when I want to drag then I got this Exception:

java.lang.ClassCastException: MyClass cannot be cast to javax.swing.tree.DefaultMutableTreeNode.

How to solve it? I need use MyClass instead of DefaultMutableTreeNode.

1

There are 1 answers

0
dic19 On

Inspecting the example you are following and given you say you get the exception when you want to drag a node, I think this is the line (not the only line that has to be fixed though):

class TreeDragSource implements DragSourceListener, DragGestureListener {
    ...
    public void dragGestureRecognized(DragGestureEvent dge) {
        TreePath path = sourceTree.getSelectionPath();
        if ((path == null) || (path.getPathCount() <= 1)) {
          // We can't move the root node or an empty selection
          return;
        }
        oldNode = (DefaultMutableTreeNode) path.getLastPathComponent(); // ClassCastException Here!
        transferable = new TransferableTreeNode(path);
        source.startDrag(dge, DragSource.DefaultMoveNoDrop, transferable, this);
    }
    ...
}

So, if your TreeModel contains only MyClass type of node (I'm asssuming your class implements at least TreeNode interface, better if MutableTreeNode) then you would have to down-cast the last path component to your class, accordingly:

    public void dragGestureRecognized(DragGestureEvent dge) {
        ...
        oldNode = (MyClass) path.getLastPathComponent();
        ...
    }

As I've said, you would have to replace all the down-casts from DefaultMutableTreeNode to MyClass. Of course this might cause other kind of exceptions but go one step at the time.