0

我想做拖放JTree。我遵循本教程:

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

不幸的是,我有JTree自己的类的节点,当我想拖动时,我得到了这个异常:

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

如何解决?我需要使用MyClass而不是DefaultMutableTreeNode.

4

1 回答 1

0

检查您正在遵循的示例并假设您说当您想要拖动节点时遇到异常,我认为这是行(虽然不是唯一必须修复的行):

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();
        ...
    }

正如我所说,您将不得不替换从DefaultMutableTreeNodeto的所有向下转换MyClass。当然,这可能会导致其他类型的异常,但一次走一步。

于 2014-12-23T14:33:38.257 回答