Java getUserObject() return 字符串而不是用户对象

Java getUserObject() return string instead of userobject

创建节点后,我想获得一个 MyNodeUserObject,以便稍后调用 getFlops() 方法。但是我无法将用户对象转换为 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.class

public 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);Parent;Flops
我的范围;真实; ;
a;false;my ranges;AA,AKs,AKo
b;false;我的范围;66,55,44,33,22
c;false;我的范围;JJ,TT,99,88

查看您在评论中链接的代码,树的根节点实际上确实包含 String ("Ranges") 作为其 userObject.

鉴于此,您的选择是

  • MyNodeUserObject周围的节点替换根节点;这可能需要对 class 进行一些更改才能正确处理根节点
  • visitAllNodes 方法中添加特殊情况(例如检查 instanceof MyNodeUserObject
  • 确保 visitAllNodes 不使用根节点调用