001package jmri.util.swing; 002 003import javax.swing.tree.DefaultMutableTreeNode; 004import org.jdom2.Element; 005 006/** 007 * Common utility methods for working with JTrees. 008 * <p> 009 * Chief among these is the loadTree method, for creating a tree from an XML 010 * definition 011 * 012 * @author Bob Jacobsen Copyright 2003, 2010 013 * @since 2.9.4 014 */ 015public class JTreeUtil extends GuiUtilBase { 016 017 /** 018 * @param name XML file to be read and processed 019 * @param wi WindowInterface to be passed to the nodes in the tree 020 * @param context Blind context Object passed to the nodes in the tree 021 * @return a mutable tree node 022 */ 023 static public DefaultMutableTreeNode loadTree(String name, WindowInterface wi, Object context) { 024 Element root = rootFromName(name); 025 026 return treeFromElement(root, wi, context); 027 } 028 029 /** 030 * @param main Element to be processed 031 * @param wi WindowInterface to be passed to the nodes in the tree 032 * @param context Blind context Object passed to the nodes in the tree 033 * @return a mutable tree node 034 */ 035 static DefaultMutableTreeNode treeFromElement(Element main, WindowInterface wi, Object context) { 036 String name = "<none>"; 037 Element e = main.getChild("name"); 038 if (e != null) { 039 name = e.getText(); 040 } 041 042 DefaultMutableTreeNode node = new DefaultMutableTreeNode(name); 043 node.setUserObject(actionFromNode(main, wi, context)); 044 045 main.getChildren("node").stream().forEach((child) -> { 046 node.add(treeFromElement(child, wi, context)); 047 }); 048 return node; 049 } 050}