• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

How can I use JTree to represents Object

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you use DefaultMutableTreeNode as your nodes, you can just use the getUserObject() and setUserObject() methods.
 
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
    HTH
    Ashish Hareet
     
    Greenhorn
    Posts: 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    You can override the toString() method in your userdefined class to return the String that will be displayed on the DefaultMutableTreeNode node.
     
    reply
      Bookmark Topic Watch Topic
    • New Topic