繁体   English   中英

如何获取jtree中每个节点的唯一ID或值?

[英]How to get unique id or value of every node in jtree?

我是jtree的新手。 我想获得具有相同父节点的单个节点的唯一ID或值。

我尝试使用valuechanged()方法,但我只能得到每个节点的字符串值。

我想比较当前选择节点与特定节点的一些唯一值。 我怎样才能实现这一目标?

我想我已经说清楚了。

有没有可能吗?

提前致谢..

TreeNode有一个getParent()方法,你可以将返回的对象引用与==进行比较。

如果您确实需要基于对象标识的唯一ID,请考虑System.identityHashCode。 请参阅以下问题: 当覆盖toString()和hashCode()时,如何获取java中对象的“对象引用”?

我一直在为DefaultMutableTreeNode设置唯一的Id。 一种方法是创建一个简单的CustomUserObject类,它具有两个属性,Id和Title。 然后,我们可以将CustomUserObject实例指定为Node UserObject属性。

要确保只在Tree结构中显示Title,请覆盖CustomUserObject类中的toString()方法。

/* CustomUserObjectClass */

public class CustomUserObject implements Serializable {

    private int Id = 0;
    private String Title = null;

    public CustomUserObject(int id, String title) {

        this.Id = id;
        this.Title = title;

    }

    public CustomUserObject() {

    }

    public int getId() {
        return this.Id;
    }

    public String getTitle() {
        return this.Title;
    }

    public void setId(int id) {
        this.Id = id;
    }

    public void setSutTitle(String title) {
        this.sutTitle = title;
    }

    @Override
    public String toString() {
        return this.Title;

    }  

现在创建一个新节点:

CustomUserObject uObj = new CustomUserObject(1, "My First Node");
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(uObj);

uObj = childNode.getUserObject();
uObj.getId();
uObj.getTitle();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM