users
[Top] [All Lists]

Re: [cinjug-users] JTree Question (more headaches)

To: Brian Engel <BEngel@xxxxxxxxxxxxx>
Subject: Re: [cinjug-users] JTree Question (more headaches)
From: Eric Galluzzo <egalluzzo@xxxxxxxxxxxxxxx>
Date: Fri, 27 Jun 2003 16:40:49 -0400
Cc: users@xxxxxxxxxx
Delivered-to: mailing list users@cinjug.org
In-reply-to: <sefc6d17.064@208.44.95.30>
Mailing-list: contact users-help@cinjug.org; run by ezmlm
References: <sefc6d17.064@208.44.95.30>
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624
Brian Engel wrote:

Just when I think I understand JTree.... :-)


Say you create a JTree with the property JTree.setEditable() set to true, using DefaultMutableTreeNodes with a custom "userObject" i.e. using the constructor like DefaultMutableTreeNode(myObject).


Whenever you edit the node in the tree (i.e. you click and pause on the text) JTree (or something) is replacing your userObject (myObject), with a new String object.

I understand why it is doing this, it constructs the text visible in the nodes by calling 
the toString method of myObject but I don't tell it how to update the text in my class; 
that is, it is a "one-way street". I want to know how/where I can change this 
behavior such that when I user edits the text in the node(Textfield) I can update 
myObject without it defaulting to a String class.

You probably need to define your own TreeCellEditor (http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/tree/TreeCellEditor.html). The getTreeCellEditor() method is called when the tree needs the component (i.e. the text field) that edits the tree node (in your case, a DefaultMutableTreeNode). Then, when you have finished editing, the tree calls getCellEditorValue() to obtain the new value of the node. It sounds like in your case, this is returning a String, which may or may not be OK. Then, that value is passed back to the TreeModel via valueForPathChanged(), and the tree model can do whatever it likes with the node. I don't know for sure, but I assume that what's happening is that DefaultTreeModel.valueForPathChanged() takes the edited value -- in your case, a string -- and puts it as the user object inside the DefaultMutableTreeNode.

Personally, I always use my business objects as the actual tree nodes and create small custom TreeModels and TreeRenderers; I almost never use DefaultTreeModel. I really like this approach; I find it to be "purer" MVC and it seems to produce less code. However, you may prefer the other method, which is fine too. :)

   - Eric



<Prev in Thread] Current Thread [Next in Thread>