创建节点后,我想获取MyNodeUserObject,以便稍后可以调用getFlops()方法。但是我无法将userobject强制转换为MyNodeUserObject。创建节点:MyNodeUserObject userObject = new MyNodeUserObject("aaa","AA-10");DefaultMutableTreeNode node = new DefaultMutableTreeNode(userObject);public static void visitAllNodes(DefaultMutableTreeNode node, JTree tree) { //java.lang.ClassCastException: java.lang.String cannot be cast to MyNodeUserObject MyNodeUserObject nodeInfo = (MyNodeUserObject) node.getUserObject();MyNodeUserObject.classpublic final class MyNodeUserObject{ private static final long serialVersionUID = 1L; private final String flops; private final String nodeName; public MyNodeUserObject(String nodeName, String flops) { this.flops = flops; this.nodeName = nodeName; } public String getFlops() { return flops; } public String getNodeName() { return nodeName; } @Override public String toString() { return nodeName; }tree.txt的内容:节点名称; IsFolder(true / false);父级;触发器我的范围;一个;错误;我的范围; AA,AKs,AKob; false;我的范围; 66,55,44,33,22c; false;我的范围; JJ,TT,99,88 最佳答案 查看在注释中链接的代码,树的根节点实际上确实包含String(“ 范围 ”)作为其userObject。鉴于此,您的选择是将根节点替换为MyNodeUserObject附近的节点;这可能需要对该类进行一些更改才能正确处理根节点在visitAllNodes方法中添加一个特殊情况(例如,检查instanceof MyNodeUserObject)确保没有用根节点调用visitAllNodes关于java - Java getUserObject()返回字符串而不是userobject,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52587834/
10-09 04:08