jQuery in Action, 3rd edition
The moose likes Swing / AWT / SWT and the fly likes How can I use JTree to represents Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How can I use JTree to represents Object" Watch "How can I use JTree to represents Object" New topic

How can I use JTree to represents Object

BJon Jo

Joined: May 21, 2003
Posts: 9
I know how to create node with String as a name in the Tree. However I don't know how to associate object with tree. It will be great if u guys have some code as an example.
Thank You very much.
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

If you use DefaultMutableTreeNode as your nodes, you can just use the getUserObject() and setUserObject() methods.

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Ashish Hareet
Ranch Hand

Joined: Jul 14, 2001
Posts: 375
I came across a similar problem a few days ago. The problem was, once you've set the user object of the node to your self defined objects how do you render it i.e is to say "How can I get the tree to get the name of the object it'll use as the String on the node from one of my objets methods ?".
Here's how I was able to do it -
  • I subclassed JTree to override the convertValueToTextMethod. This method is called by the renderer code to get the String represented by the object at a node.
  • The object passed to the convertValueToText method is a MutableTreeNode object(I'm not sure yet) from which you can get your object by calling the getUserObject().
  • Now in your overridden method you have your user object from which you can get it's String representation(by calling one of your objects methods) & return this value.

  • And now your tree will show the Strings for objects the way you'd like them.
    Ashish Hareet
    Vidhya Murali

    Joined: Jun 30, 2003
    Posts: 2
    You can override the toString() method in your userdefined class to return the String that will be displayed on the DefaultMutableTreeNode node.
    I agree. Here's the link: http://aspose.com/file-tools
    subject: How can I use JTree to represents Object
    It's not a secret anymore!