Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

programmatically select a tree node

 
Alan Shiers
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First off, this should be posted in the Swing forum. Second, it's been a while since I worked with JTrees, but I suspect that you are trying to add a node on a thread other than the swing event thread. Remember most swing components are not thread safe. Usually you will get a flurry of exceptions when you try to change a swing component on the wrong thread, sometimes it just seems to ignore you. There are a couple of ways around this. You can use SwingUtilities.InvokeLater(Runnable runner) or SwingUtilities.invokeAndWait(Runnable runner), or you can do the update using javax.swing.Timer and provide an ActionListener since javax.swing.Timer runs on the swing event thread. Without running your code, I can't say for sure what the problem is, but this is a common problem that many developers have when they first start working with swing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic