Mani Prasad
Mani Prasad

Reputation: 31

Scrolling a tree node to top of a scroll pane

I have a JTree with about more than 8 tree nodes(leafs). The requirement is if user clicks on a tree node, the selected tree node will automatically scrolls to top of the scroll pane from any position. Please help!

Upvotes: 3

Views: 3530

Answers (3)

Igwe Kalu
Igwe Kalu

Reputation: 14868

This question was asked a long time ago, and I don't know if you still need this...

I understand the problem you have, the issue is this: tree selection listeners don't work as you might expect. You have to detect the click event by registering a mouse listener. Something like this:

tree = new JTree();
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    MouseListener ml = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            int selRow = tree.getRowForLocation(e.getX(), e.getY());
            currentRow = selRow;
            TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
            if (selRow != -1) {
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(selPath.getLastPathComponent());
                if (node != null && node.isLeaf()) {
                    String stringId = '<sting-id-of-node-you-wish-to-scroll-to>';
                    TreePath tp = tree.getNextMatch(stringId, currentRow, Position.Bias.Forward);
                    if (tp == null) {
                        tp = tree.getNextMatch(stringId, currentRow, Position.Bias.Backward);
                    }
                    tree.setSelectionPath(tp);
                    tree.scrollPathToVisible(tp);
                }
            }
        }
    };
    tree.addMouseListener(ml);

Cheers!

Upvotes: 1

kleopatra
kleopatra

Reputation: 51525

As already noted: all scrollXXToVisible methods scroll such that the given XX is visible somewhere, they don't support finer control as f.i. "should be first node in visible area".

You have to implement that functionality yourself, something like

TreePath path = tree.getSelectionPath();
if (path == null) return;
Rectangle bounds = tree.getPathBounds(path);
// set the height to the visible height to force the node to top 
bounds.height = tree.getVisibleRect().height;
tree.scrollRectToVisible(bounds);

Beware: doing so in reaction to a mouse event on the node might be annoying to the user as it moves the target from under its feet.

Upvotes: 3

jzd
jzd

Reputation: 23629

Use the scrollRectToVisible method on the actual JTree.

Example:

tree.scrollRectToVisible(new Rectangle(0,0));

Upvotes: 2

Related Questions