1

I have a Jtree that I can add new Nodes to. I need to assign a unique ID to each new node. I was thinking of extending the DefaultMutableTreeNode Class but I guess it didn't work or I did it wrong.

So, how can I do this. An example would be nice. Thanks.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Igor
  • 1,532
  • 4
  • 23
  • 44
  • 4
    If you showed us what you tried, we could tell you what you did wrong. – JB Nizet Sep 25 '12 at 17:05
  • [this code](http://www.java2s.com/Tutorial/Java/0240__Swing/implementsTreeModel.htm) you can to use for your [SSCCE](http://sscce.org/) and/or with detailed describtion about – mKorbel Sep 25 '12 at 17:11
  • @JBNizet I already deleted it. Would extending it work? If it does can you give an example, I suppose it's pretty short? – Igor Sep 25 '12 at 17:15

2 Answers2

2

My impression is that DefaultMutableTreeNode works "best" without extending it, but wrapping your own user-defined object. And that could have an ID.

Nevertheless your way should work too, when creating a nodes children with your own class. A matter of debugging, and trace logs: creation of all objects and such. Mind that one can easily err in the API and several times create TreeNode-s for a child.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • +1 That's been my experience; there's an example [here](http://stackoverflow.com/a/11113648/230513). – trashgod Sep 25 '12 at 19:18
0

OK I figured it out and it WORKS :) I extednded DefaultMutableTreeNode:

 public class MyTreeNode extends DefaultMutableTreeNode {

    public int ID;

    public void setID(int ID) {
        this.ID = ID;
    }

    public MyTreeNode(String title) {
        setUserObject(title);
    }
}
Igor
  • 1,532
  • 4
  • 23
  • 44
  • 1
    There is no need for this. You can pass any `Object` as user object, which includes an object containing that ID. – Robin Sep 25 '12 at 17:45
  • See the linked example in @trashgod comment on the other answer – Robin Sep 26 '12 at 05:43