简体   繁体   中英

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

I am new to jtree. I want to get the unique id or value of individual nodes which have same parent.

I tried with valuechanged() method, but i am able to get only the string value of every node.

I want to compare the current selecting node with some unique value of particular node. How can i achieve this?

I think i am making clear.

Is there any possibilites available?

Thanks in advance..

TreeNode has a getParent() method, you can compare the object reference returned with it with ==.

If you really need an unique id based on object identity, consider System.identityHashCode. See the following question: How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

I have been working on setting a unique Id for the DefaultMutableTreeNode. One method is to create a simple CustomUserObject Class which has tow properties, Id and Title. We can then assign the CustomUserObject instance as the Node UserObject property.

To make sure that only the Title is displayed in the Tree structure, override the toString() method in the CustomUserObject Class.

/* 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;

    }  

Now to create a new node:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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