Java Swing: how to determine how JTree displays a "custom object"?

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

How to change the way a user object is displayed?

NOTE. My user object must be something other than String in order to be able to maintain a mapping between the tree and the user objects.

+4
source share
3 answers

I do not understand what the problem is.

DefaultMutableTreeNode will use the toString method for the user object because it makes sense. JTree needs strings to draw objects, so the request to your object will look fine.

If you really need to avoid calling toString on your object, you'll need a way to provide a string representing 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 see no reason to do this. Alternatively, you can try extending DefaultMutableTreeNode by overriding the toString method, but you will need an additional reference to your object, or you will need some downgrades.

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

+6
source

Override toString () in your custom object OR provide TreeCellRenderer , a basic example

+5
source

Another alternative if you just need the text shown for the user object and you don't want to worry about TreeCellRender: extend JTree and override convertValueToText with your own code that creates a descriptive line for this object.

0
source

Source: https://habr.com/ru/post/1305973/


All Articles