【问题标题】:ClassCastException while Drag and Drop in a JTree在 JTree 中拖放时发生 ClassCastException
【发布时间】:2014-12-22 13:00:28
【问题描述】:

我想在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

【问题讨论】:

  • 你在哪一行有异常?请分享您的代码的相关部分,或者最好尝试发布MCVE 来展示您的问题(您可能会在制作 MCVE 的过程中解决您的问题)。
  • 另一方面,异常是不言自明的:您试图将MyClass 对象转换为DefaultMutableTreeNode。如果您的 TreeModel 仅包含 MyClass 节点类型,则相应地将向下转换替换为 MyClass。例如:MyClass parent = (MyClass) parentpath.getLastPathComponent();

标签: java swing drag-and-drop jtree defaultmutabletreenode


【解决方案1】:

检查the example 您正在关注并假设您在想要 drag 一个节点时遇到异常,我认为这是行(虽然不是唯一必须修复的行):

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 替换为 MyClass。当然,这可能会导致其他类型的异常,但一次走一步。

【讨论】:

    猜你喜欢
    • 2011-06-03
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    相关资源
    最近更新 更多