Java examples for Swing:JTree
Adding a Node to a JTree Component
import javax.swing.JTree; import javax.swing.text.Position; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreePath; public class Main { public void m() { JTree tree = new JTree(); DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); // Find node to which new node is to be added int startRow = 0; String prefix = "J"; TreePath path = tree.getNextMatch(prefix, startRow, Position.Bias.Forward); MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent(); // Create new node MutableTreeNode newNode = new DefaultMutableTreeNode("green"); // Insert new node as last child of node model.insertNodeInto(newNode, node, node.getChildCount()); }//from ww w. j av a2s . co m }