File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes selecting a JTree node programmatically Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "selecting a JTree node programmatically" Watch "selecting a JTree node programmatically" New topic
Author

selecting a JTree node programmatically

Alan Shiers
Ranch Hand

Joined: Sep 24, 2003
Posts: 237
Hi there,
Given a TreePath object, I need to know how to programmatically select a tree node on a JTree.
Here's the situation:
I have a simple text editor project which has a JTree on its interface representing the local file system. The program has a SaveAs dialog box which also has a duplicate JTree as the one on the main interface (directories only). As the user selects the directory in which they wish to save the open file in the SaveAs dialog box, I need somehow to programmatically cause the JTree on the main interface to correspondingly select the same directory. How is this done?
The whole point of this is so that I can then add a new leaf node to the tree at the specified directory location. I've tried simply setting the jTree1.setSelectionPath(...) method and even tried to call the valueChanged(...) method of the TreeSelectionListener object as you can see from the code snippet below, but none of these approaches have been successful.
Please advise,
Alan

Joe Gilvary
Ranch Hand

Joined: May 11, 2001
Posts: 152
Your code example is confusing to me. Is JTree1 the JTree or is it an implementation of TreeModel? You call setSelectionPath() and nodeStructureChanged() on the same object. Are you subclassing JTree and implementing TreeModel yourself in a single class? Implementing TreeModel is a lot of work.
I have used setSelectionPath() successfully in a mouse listener without needing to call the SelectionEventListener from there at all. I think it's unusual to have to call that method yourself.
I've been able to add nodes to a JTree with code like this:

(The loader persists menu structure data back to a database. myModel is an instance of DefaultTreeModel. xfer is declared Transferable and cast to my own class after it passes the transfer flavor checks.)
The O'Reilly "Swing" book and their "Java Foundation Classes in a Nutshell" were a lot of help to me with this stuff. Well worth the money, especially if you will be doing more of this kind of work.
HTH,
Joe
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: selecting a JTree node programmatically