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
.
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):
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:As I've said, you would have to replace all the down-casts from
DefaultMutableTreeNode
toMyClass
. Of course this might cause other kind of exceptions but go one step at the time.