views:

78

answers:

2

Hello, everyone!

When using a JTree, a "user object" of a DefaultMutableTreeNode can be set. This can be of any kind, but to display it, its toString() value is used. This is not what I need.

How can I change the way a user object is displayed?

NOTE: My user object has to be something different than a String to be able to maintain mapping between the tree and the user objects.

+2  A: 

Override toString() on your user object OR provide a TreeCellRenderer, basic example

basszero
+1 for TreeCellRenderer.
Donal Fellows
I'd keep the renderers as thin as possible.
Tom Hawtin - tackline
+2  A: 

I don't get what's your problem.

The DefaultMutableTreeNode will use the toString method on the user object because it makes sense. The JTree needs strings to draw objects so asking to your object its string rapresentation is ok.

If you really need to avoid calling toString on your object you will need a way to provide a string rapresentation of it anyway, but you will have to write your own MutableTreeNode:

class MyTreeNode implements MutableTreeNode
{
  UserObject yourObject;

  MyTreeNode(UserObject yourObject)
  {
    this.yourObject = yourObject;
  }

  // implement all needed methods to handle children and so on

  public String toString()
  {
    // then you can avoid using toString
    return yourObject.sringRapresentation();
  }
}

But I really don't see the point of doing this.. in addition you can try extending the DefaultMutableTreeNode by overriding toString method, but you will need an additional reference to your object or some downcasts will be needed.

If you really need a different visualization than a string you will have to write your own rendered that implements TableCellRenderer.

Jack
That was exactly my problem: I didn't know that overriding `DefaultMutableTree`'s `toString()` in this case is the same as overriding `toString()` of the user object (which by the way is final and from an external API, so I couldn't do it).
java.is.for.desktop