Why do you have a tree model listener? Are you modifying the nodes at runtime, after the tree is displayed? Usually, one uses a tree selection listener to figure out user selection.
When the tree nodes changed is fired, which node is selected on the UI? Is it the root? Is the root also constructed using the Directory object?
I created a simple tree like this
Then I added a selection listener to the tree and I print out the node's user object. If I select one of the drives, I correctly get java.io.File on the console. But if I select the root, I get java.lang.String
Is something similar happening in your case?
If not, you will need to post sscce code for us to help you. Please do visit the link to find out what sscce really means.
Yes, I am changing the nodes at running time (set the JTree as editable)
I found an user with exactly the same issue I have in that link "http://220.127.116.11/thread.jspa?messageID=2232016" with the subject:
Swing [Archive] - getUserObject() should really return my object, not a String object.
Look what I found.... (I believe that the previous person could explain better the issue than I)
When you edit a treenode, the tree sets the user object ot be a string, because it doesn't know any better...
The TreeCellRenderer (I believe) is responsible for the call to the TreeModel.valueForPathChanged(TreePath p,Object value) and it passes a String which it obtains from its editor component (a JTextField).
DefaultTreeModel then calls, MutableTreeNode.setUserObject(), hence the resulting String.
You have two choices:
1) rewrite TreeCellEditor to parse the String into your Thing
2) rewrite the DefaultTreeModel to convert the String to your Thing
Let me know if you know a easier way to fix that...
Joined: Sep 03, 2003
Just to close this thread I will add the code and some of the references I used to persist the original userObject after changes in an editable tree node.
I understood that whenever you use custom objects instead of "Strings" you will need to do that.
A very good explanation about how to work with JTree can be found in the book
"Core JFC, 2nd Edition By Kim Topley" (I could find the chapter about JTree in the web...)
"To ensure that the value stored in a node after the edit has completed is an object of the correct type, it will be necessary to supply our own tree model in which the valueForPathChanged method is overridden."
In see below my TreeModel
When treeNodesChanged is called I did:
My user object ...
This worked for me, however, I am not a Java professional and probably there are better ways to do it but I am happy with the results.
Maybe this can help someone else (I took alot of time to find out that ))))