jtree对于指定节点,怎么开启和关闭呢?下面写两个方法,供大家参考。
package com.sysc.xmleditor.utils; import java.awt.event.MouseEvent; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; /** * jtree帮助类 * @author Administrator * */ public class TreeHelp { /** * 展开指定节点所有后代节点 * @param aTree展开所有节点,后代节点层层展开 * @param aNode */ public static void expandTreeNode(JTree aTree, DefaultMutableTreeNode aNode) { if (aNode.isLeaf()) { return; } aTree.expandPath(new TreePath( ( (DefaultMutableTreeNode) aNode).getPath())); int n = aNode.getChildCount(); for (int i = 0; i <n; i++) { expandTreeNode(aTree, (DefaultMutableTreeNode) aNode.getChildAt(i)); } } /** * 关闭指定节点所有后代节点 * @param aTree,直接关闭指定节点 * @param aNode */ public static void collapseTreeNode(JTree aTree, DefaultMutableTreeNode aNode) { if (aNode.isLeaf()) { return; } TreePath path=new TreePath(aNode.getPath()); aTree.collapsePath(path); } /** * 通过鼠标的位置找到选择的位置 * @param tree * @param e */ public static void selectTreeElem_Mouse(JTree tree,MouseEvent e) { TreePath path = getPathByMouse(tree, e); tree.setSelectionPath(path); } /** * 返回鼠标最近的treePath节点 * @param tree * @param e * @return */ public static TreePath getPathByMouse(JTree tree,MouseEvent e){ TreePath path = tree.getPathForLocation(e.getX(),e.getY());//选择鼠标最近的节点的条目 return path; } }