[英]ClassCastException while Drag and Drop in a JTree
我想在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
。
檢查下面的示例 ,並說要拖動節點時會得到異常,我認為這是一行(盡管不是唯一必須修復的行):
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
。 當然,這可能會導致其他類型的異常,但在那時只能邁出一步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.