Find a Node in a JTree Component in Java
Description
The following code shows how to find a Node in a JTree Component.
Example
//from w ww. j a v a 2 s . c o m
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
root.add(mercury);
DefaultMutableTreeNode venus = new DefaultMutableTreeNode("b");
root.add(venus);
DefaultMutableTreeNode mars = new DefaultMutableTreeNode("java2s.com");
root.add(mars);
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
// Search forward from first visible row looking for any visible node
// whose name starts with prefix.
int startRow = 0;
String prefix = "b";
TreePath path = tree.getNextMatch(prefix, startRow, Position.Bias.Forward);
System.out.println(path);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »