Raven
Raven

Reputation: 3526

Mark treeNode as selected (Swing)

I have a simple JTree.
I set it's selected node in the code via setSelectionPath().

Everything works fine for that but what I want is that the respective node (the end of my path) is highlighted as if the user had clicked on it with the mouse so that there is also a visual feedback in the tree itself to indicate which node is selected.

Greetings Raven

EDIT:
How I want it to look (just like it looks when selecting a node with the mouse Properly highlighted (after selection with mouse)

How it currently looks after selecting node via program Current result after selecting node via program

Upvotes: 0

Views: 1163

Answers (2)

Raven
Raven

Reputation: 3526

I found my problem:
I was refreshing the content of my tree when selecting the pane where the tree is located on.
But instead of just updating it's nodes I recreated the complete model and that was the problem.
The path I was using was a path of the old model and this is the reason why the path couldn't be properly selected in the new tree. I switched to the approach of just updating the model and now setSelectionPath() has the effect I wanted it to have.

Upvotes: 0

Leet-Falcon
Leet-Falcon

Reputation: 2147

To focus and expand the selected node:

  1. jtree.setScrollsOnExpand(true)

    Determines whether the tree might scroll to show previously hidden children.
    If this property is true (the default), when a node expands the tree can use scrolling to make the maximum possible number of the node's descendants visible.

  2. jtree.setExpandsSelectedPaths(true)
    Allows to configure the JTree to automatically expand selected paths.
    If you want to manage this manually,
    you can use jtree.setExpandedState(TreePath path, boolean state) method

Upvotes: 1

Related Questions