Scrolling a node tree to the top of the scroll bar

I have JTreewith over 8 tree nodes (leaves). The requirement is that if the user clicks on the node tree, the selected node tree will automatically scroll to the top of the scroll bar from any position. Please, help!

+3
source share
3 answers

As already noted: all scrollXXToVisible methods scroll so that the given XX is visible somewhere, they do not support finer control like fi "should be the first node in the visible area".

You must implement this 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);

: node , - .

+3

scrollRectToVisible JTree.

:

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

This question has been asked for a long time, and I do not know if you need this information ...

I understand your problem, the problem is that tree select listeners do not work as you might expect. You should detect a click event by registering a mouse listener. Something like that:

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);

Hooray!

+1
source

All Articles