I have easily looked at 30 sites (including this one) trying to find a solution to the problem of a JTree not scrolling to a selected node. My JTree, which is in a JScrollPane, does have the proper node selected and highlighted; but I cannot get the scrollpane to cooperate.
Most every site I have found (with entries going back to 2002) are all similiar to http://www.coderanch.com/t/334800/GUI/java/jtree-not-scrolling-selected-node, which prescribes calling either scrollPathToVisible(treePath) or scrollPathToVisible(row). I have also tried scrollRectToVisible(Rectangle) on the JViewport of the JScrollPane in which the JTree resides. I have also tried manually setting the value on the JScrollBar itself, all to no avail.
I cannot provide the full code; but here is the snippet and the output I receive.
Construction for my JTree:
Upon starting up the application, I start a progress task, which loads the tree with nodes from a cache/database. After it completes, it calls a method that successfully expands and selects the node (node is last node selected when shut down application). What it does not do is scroll to the selected node.
The output from the System.out's above is:
There has to be something simple that I am missing or not understanding, but, like I said, I have tried solutions on at least 30 sites and nothing has worked.
Can anyone point me to what might be causing the problem? I mean, I have tried manually setting the vertical scrollbar value and even THAT did not work.
start another project
add a simple JTree() - empty constructor (will give you nodes of colors/sports/food)
try scrolling to (pre) selected node
if it works, replace this
"Upon starting up the application, I start a progress task, which loads the tree with nodes from a cache/database."
with some hard coded data - just a few items
recompile, try again
if it still works OK, add one line at a time of these tree changes
this.jtTree.putClientProperty( "JTree.lineStyle", "Angled" );
when you get to the point of it not working, post that code (all of it, so we can copy/paste/compile/run/observe)
posted 8 years ago
Thanks for the exercise, it helped find the problem. I was setting the tree node before it was added to the scroll pane. As expected (and documented), calling scrollRowToVisible() at that point did nothing, since it was not in a scrollable pane. Putting the setCurrentNode just after adding to the scroll pane immediately fixed the issue.
Sorry to have bothered the reader(s) and thanks again.