检查您正在遵循的示例并假设您说当您想要拖动节点时遇到异常,我认为这是行(虽然不是唯一必须修复的行):
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);
}
...
}
因此,如果您的TreeModel仅包含MyClass
节点类型(我假设您的类至少实现了TreeNode接口,如果MutableTreeNode更好)那么您将不得不将最后一个路径组件向下转换为您的类,因此:
public void dragGestureRecognized(DragGestureEvent dge) {
...
oldNode = (MyClass) path.getLastPathComponent();
...
}
正如我所说,您将不得不替换从DefaultMutableTreeNode
to的所有向下转换MyClass
。当然,这可能会导致其他类型的异常,但一次走一步。