0

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.

dic19
  • 17,821
  • 6
  • 40
  • 69
rizon
  • 13
  • 6
  • At which line do you have the exception? Please share the relevant part of your code, or even better try to post a [MCVE](http://www.stackoverflow.com/mcve) demonstrating your problem (you might solve your problem in the process of making an MCVE). – dic19 Dec 23 '14 at 13:28
  • On the other hand, the Exception is pretty self-explanatory: you are trying to cast a `MyClass` object as `DefaultMutableTreeNode`. If your `TreeModel` contains only `MyClass` node type then replace the down-casts to `MyClass` accordingly. For example: `MyClass parent = (MyClass) parentpath.getLastPathComponent();` – dic19 Dec 23 '14 at 13:35

1 Answers1

0

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.

dic19
  • 17,821
  • 6
  • 40
  • 69