Java Swing How to - Scroll to display the selected path








Question

We would like to know how to scroll to display the selected path.

Answer

import java.awt.BorderLayout;
//  w  ww .j  ava 2s . c  om
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.text.Position;
import javax.swing.tree.TreePath;

public class Main {
  JTree tree = new JTree();

  Main() {
    JPanel p = new JPanel(new BorderLayout(2, 2));
    JTextField find = new JTextField("food:pizza");
    find.addActionListener(e->{
        boolean found = findText(find.getText());
        System.out.println(find.getText() + " found " + found);
    });
    p.add(find, BorderLayout.PAGE_START);
    tree.setVisibleRowCount(8);
    for (int row = tree.getRowCount(); row >= 0; row--) {
      tree.expandRow(row);
    }
    p.add(new JScrollPane(tree), BorderLayout.CENTER);
    JOptionPane.showMessageDialog(null, p);
  }

  public boolean findText(String nodes) {
    String[] parts = nodes.split(":");
    TreePath path = null;
    for (String part : parts) {
      int row = (path == null ? 0 : tree.getRowForPath(path));
      path = tree.getNextMatch(part, row, Position.Bias.Forward);
      if (path == null) {
        return false;
      }
    }
    tree.scrollPathToVisible(path);
    tree.setSelectionPath(path);
    return path != null;
  }
  public static void main(String[] args) {
    new Main();
  }
}