用纯java自定义自己的树形菜单

用纯java自定义自己的树形菜单

转自

small_ding的专栏

 

1.定义每个树节点信息的类

package BSC.tree;

import java.io.*;

import java.util.*;

/**

 * <p>一个树节点对像 </p>

 * <p>构造一个树节点对像 </p>

 * <p>Copyright: Copyright (c) 2003</p>

 * <p>上海佳杏 </p>

 * @author 丁小龙

 * @version 1.0

 */

 

public class clsTreeNode implements Serializable {

    /**

     * 根据指定参数构造一个新的 clsTreeNode 节点

     *

     * @param name 节点内在名字 (在整个棵树中必须是唯一的)

     * @param icon 节点可见时相对于图像目录的完整图橡文件的路径名

     * @param label 节点可见时的标签内容

     * @param action 当前所选择节点的对应的超级链接,若为空没有超级链接

     * @param target 超级链接所对应的窗口对象,若为空为当前窗口

     * @param expanded 节点是否展开?

     */

    public clsTreeNode(String name,

                           String icon, String label,

                           String action, String target,

                           boolean expanded, String domain) {

 

        super();

        this.name = name;

        this.icon = icon;

        this.label = label;

        this.action = action;

        this.target = target;

        this.expanded = expanded;

        this.domain = domain;

 

    }

    protected String labelcolor="#0000FF";

    public String getLabelColor()

    {

      return this.labelcolor;

    }

    public void setLabelColor(String color)

    {

      if(color!=null)

        this.labelcolor=color;

    }

 

    // ----------------------------------------------------- 实体变量

 

 

    /**

     * 当前节点的子节点集,他们按一定的顺序显示, in the

     */

    protected Vector children = new Vector();

 

 

 

 

    /**

     * 假如节点被选择将直接被超级链接所控制

     */

    protected String action = null;

 

    public String getAction() {

        return (this.action);

    }

 

    /**

     * 节点的域.

     */

    protected String domain = null;

 

    public String getDomain() {

        return (this.domain);

    }

 

    /**

     * 节点当前是否被展开?

     */

    protected boolean expanded = false;

 

    public boolean isExpanded() {

        return (this.expanded);

    }

 

    public void setExpanded(boolean expanded) {

        this.expanded = expanded;

    }

 

 

    /**

     *节点可见时相对于图像目录的完整图橡文件的路径名

     */

    protected String icon = null;

 

    public String getIcon() {

        return (this.icon);

    }

 

 

    /**

     *节点可见时的标签内容.

     */

    protected String label = null;

 

    public String getLabel() {

        return (this.label);

    }

 

 

    /**

     * 是否当前父节点的子节点集中的最后一个节点

     */

    protected boolean last = false;

 

    public boolean isLast() {

        return (this.last);

    }

 

    void setLast(boolean last) {

        this.last = last;

    }

 

 

    /**

     * 是否为叶节点 ?

     */

    public boolean isLeaf() {

        synchronized (children) {

            return (children.size() < 1);

        }

    }

 

    public int getChildCount()

    {

      return children.size() ;

    }

    /**

     *节点内在名字 (在整个棵树中必须是唯一的)

     */

    protected String name = null;

 

    public String getName() {

        return (this.name);

    }

 

 

    /**

     * 当前节点的父节点,若为空为则为根节点.

     */

    protected clsTreeNode parent = null;

 

    public clsTreeNode getParent() {

        return (this.parent);

    }

 

    void setParent(clsTreeNode parent) {

        this.parent = parent;

        if (parent == null)

            width = 1;

        else

            width = parent.getWidth() + 1;

    }

 

 

    /**

     * 节点当前是否被选择

     */

    protected boolean selected = false;

 

    public boolean isSelected() {

        return (this.selected);

    }

 

    public void setSelected(boolean selected) {

        this.selected = selected;

    }

 

 

    /**

     * 超级链接所对应的窗口对象,若为空为当前窗口

     */

    protected String target = null;

 

    public String getTarget() {

        return (this.target);

    }

 

 

 

 

 

 

    /**

     * 节点的可显示宽度(如果节点为可见的).

     * 如果节点不可见,则计算出的宽度为最直接的父节点

     */

    protected int width = 0;

 

    public int getWidth() {

        return (this.width);

    }

 

 

    // --------------------------------------------------------- Public Methods

 

 

    /**

     * 添加一个新的子结点的

     *

     * @param child 新子节点

     *

     * @如果这个新子结点的名字不是唯一的则抛出 IllegalArgumentException 异常

     */

    public void addChild(clsTreeNode child)

        throws IllegalArgumentException {

 

        tree.addNode(child);

        child.setParent(this);

        synchronized (children) {

            int n = children.size();

            if (n > 0) {

                clsTreeNode node = (clsTreeNode) children.get(n - 1);

                node.setLast(false);

            }

            child.setLast(true);

            children.add(child);

        }

 

    }

 

 

    /**

     * 通过指定位置加入一个子节点

     *

     * @param offset 相对0的位移

     * @param child 欲加入的子节点

     *

     * @如果这个新子结点的名字不是唯一的则抛出 IllegalArgumentException 异常

     */

    public void addChild(int offset, clsTreeNode child)

        throws IllegalArgumentException {

 

        tree.addNode(child);

        child.setParent(this);

        synchronized (children) {

            children.add(offset, child);

        }

 

    }

 

 

    /**

     * 返回子节点集

     */

    public clsTreeNode[] findChildren() {

 

        synchronized (children) {

            clsTreeNode results[] = new clsTreeNode[children.size()];

            return ((clsTreeNode[]) children.toArray(results));

        }

 

    }

    /**

    * 整棵树的描述对像

     */

    protected clsTreeControl tree = null;

 

     public clsTreeControl getTree() {

         return (this.tree);

     }

 

    public void setTree(clsTreeControl tree) {

         this.tree = tree;

    }

 

    public void setLabel(String label) {

        this.label = label;

    }

 

    /**

     *从树中移出自己

     */

    public void remove() {

 

        if (tree != null) {

            tree.removeNode(this);

        }

 

    }

 

 

    /**

     * 从指定位置中删除一个子节点

     * @param offset 基于0 存在位置

     */

    public void removeChild(int offset) {

 

        synchronized (children) {

            clsTreeNode child =

                (clsTreeNode) children.get(offset);

            tree.removeNode(child);

            child.setParent(null);

            children.remove(offset);

        }

 

    }

 

 

    // -------------------------------------------------------- Package Methods

 

 

    /**

     *删除指定子节点,但必须是存在的

     *

     * @param child 要被删除的节点

     */

    void removeChild(clsTreeNode child) {

 

        if (child == null) {

            return;

        }

        synchronized (children) {

            int n = children.size();

            for (int i = 0; i < n; i++) {

                if (child == (clsTreeNode) children.get(i)) {

                    children.remove(i);

                    return;

                }

            }

        }

 

    }

 

 

}

2.定义控制树节点信息的类

ackage BSC.tree;

import java.io.Serializable;

import java.util.HashMap;

/**

 * <p>一棵树的完整数据结构描述,它能通过clsDrawTree类来绘制</p>

 * <p> 树的每个结点通过TreeControlNode类实例来描述</P>

 * <p>Copyright: Copyright (c) 2003</p>

 * <p>上海佳杏 </p>

 * @author 丁小龙

 * @version 1.0

 */

 

public class clsTreeControl implements Serializable {

 

 

    // ----------------------------------------------------------- 构造方法

 

 

    /**

     * 在没有预先确定的根节点构造一个新实体

     */

    public clsTreeControl() {

 

        super();

        setRoot(null);

 

    }

 

 

    /**

     * 通过指定的根节点构造一个新实体

     *

     * @param root 根节点

     */

    public clsTreeControl(clsTreeNode root) {

 

        super();

        setRoot(root);

 

    }

 

 

    // ----------------------------------------------------- 实体变量

 

 

    /**

     *按键入的名字来描述这棵树的节点集合

     */

    protected HashMap registry = new HashMap();

 

 

    /**

     * 最近被选择的节点

     */

    protected clsTreeNode selected = null;

 

 

 

 

    /**

     * 整棵树的根节点

     */

    protected clsTreeNode root = null;

 

    public clsTreeNode getRoot() {

        return (this.root);

    }

 

    public void setRoot(clsTreeNode root) {

        if (this.root != null)

            removeNode(this.root);

        if (root != null)

            addNode(root);

        root.setLast(true);

        this.root = root;

    }

 

 

    /**

     * 树当前可显示的宽 (也就是说,树可见的最深部分)

     */

    public int getWidth() {

 

        if (root == null)

            return (0);

        else

            return (getWidth(root));

 

    }

 

 

    // --------------------------------------------------------- Public Methods

 

 

    /**

     *能过指定名字返回节点,如果不存在返回空

     * @param name 被返回结点的名字

     */

    public clsTreeNode findNode(String name) {

 

        synchronized (registry) {

            return ((clsTreeNode) registry.get(name));

        }

 

    }

 

 

    /**

     * 给当前被选择的节点做一个唯一的标记,并且取消任何节点做过的标记

     * @param node 被选择节点的名字

     */

    public void selectNode(String name) {

 

        if (selected != null) {

            selected.setSelected(false);

            selected = null;

        }

        selected = findNode(name);

        if (selected != null)

            selected.setSelected(true);

 

    }

 

 

    // -------------------------------------------------------- 方法

 

 

    /**

     * 注册指定节点到已经注册的的完全树

     *

     * @param node 被注册的TreeControlNode类型对像

     *

     * @假若节点名字不唯一则抛出 IllegalArgumentException 异常

     */

    void addNode(clsTreeNode node) throws IllegalArgumentException {

 

        synchronized (registry) {

            String name = node.getName();

            if (registry.containsKey(name))

                throw new IllegalArgumentException("Name '" + name +

                                                   "' is not unique");

            node.setTree(this);

            registry.put(name, node);

        }

 

    }

 

 

    /**

     * 计算指定节点的子树的宽度

     *

     * @param node 欲计算子树的宽度的TreeControlNode对像

     */

    int getWidth(clsTreeNode node) {

 

        int width = node.getWidth();

        if (!node.isExpanded())

            return (width);

        clsTreeNode children[] = node.findChildren();

        for (int i = 0; i < children.length; i++) {

            int current = getWidth(children[i]);

            if (current > width)

                width = current;

        }

        return (width);

 

    }

 

 

    /**

     *从树中撤消指定的结点

     * @param node 要被撤消的TreeControlNode对像

     */

    public void removeNode(clsTreeNode node) {

 

        synchronized (registry) {

            clsTreeNode children[] = node.findChildren();

            for (int i = 0; i < children.length; i++)

                removeNode(children[i]);

            clsTreeNode parent = node.getParent();

            if (parent != null) {

                parent.removeChild(node);

            }

            node.setParent(null);

            node.setTree(null);

            if (node == this.root) {

                this.root = null;

            }

            registry.remove(node.getName());

        }

 

    }

 

 

}

3.定义绘制树的类

package BSC.tree ;

 

import java.io.IOException;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.JspWriter;

import javax.servlet.jsp.PageContext;

import javax.servlet.jsp.tagext.TagSupport;

/**

 * <p>一棵树的绘制类(通过clsTreeControl对像)</p>

 * <p> 树的每个结点通过TreeControlNode类实例来描述</P>

 * <p>Copyright: Copyright (c) 2003</p>

 * <p>上海佳杏 </p>

 * @author 丁小龙

 * @version 1.0

 */

 

 

public class clsDrawTree extends TagSupport {

    public clsDrawTree() {

        try {

            jbInit();

        } catch (Exception ex) {

            ex.printStackTrace();

        }

    }

 

 

    /**

     * The default directory name for icon images.

     */

    static final String DEFAULT_IMAGES = "images";

 

 

    /**

     * 所需要的状态图标文件名.

     */

    static final String TD_WIDTH="   <td width=/'5%/'>";

    static final String IMAGE_HANDLE_DOWN_LAST =    "handledownlast.gif";

    static final String IMAGE_HANDLE_DOWN_MIDDLE =  "handledownmiddle.gif";

    static final String IMAGE_HANDLE_RIGHT_LAST =   "handlerightlast.gif";

    static final String IMAGE_HANDLE_RIGHT_MIDDLE = "handlerightmiddle.gif";

 

    static final String IMAGE_HANDLE_OPEN="ftv2folderopen.gif";

    static final String IMAGE_HANDLE_CLOSE="ftv2folderclosed.gif";

 

    static final String IMAGE_LINE_LAST =           "linelastnode.gif";

    static final String IMAGE_LINE_MIDDLE =         "linemiddlenode.gif";

    static final String IMAGE_LINE_VERTICAL =       "linevertical.gif";

 

    public clsDrawTree(clsTreeControl control,PageContext pageContext)

    {

      this.pageContext =pageContext;

      this.control =control;

    }

    // ------------------------------------------------------------- Properties

 

 

    /**

     * The hyperlink to be used for submitting requests to expand and

     * contract tree nodes.  The placeholder "<code>${name}</code>" will

     * be replaced by the <code>name</code> property of the current

     * tree node.

     */

    protected String action = null;

 

    public String getAction() {

        return (this.action);

    }

 

    public void setAction(String action) {

        this.action = action;

    }

     protected clsTreeControl  control=null;

     public void setControl(clsTreeControl m)

     {

       control=m;

    }

    public clsTreeControl getControl()

     {

        return       control;

    }

    /**

     * The name of the directory containing the images for our icons,

     * relative to the page including this tag.

     */

    protected String images = DEFAULT_IMAGES;

 

    public String getImages() {

        return (this.images);

    }

 

    public void setImages(String images) {

        this.images = images;

    }

 

 

    /**

     *搜索树的范围属性,必须是e "page", "request", "session", "application"

     * (or <code>null</code> 搜索).

     */

    protected String scope = null;

 

    public String getScope() {

        return (this.scope);

    }

 

    public void setScope(String scope) {

        if (!"page".equals(scope) &&

            !"request".equals(scope) &&

            !"session".equals(scope) &&

            !"application".equals(scope))

            throw new IllegalArgumentException("Invalid scope '" +

                                               scope + "'");

        this.scope = scope;

    }

 

 

    /**

     *  CSS 类型 <code>class</code> 被应用于整棵树.

     */

    protected String style = null;

 

    public String getStyle() {

        return (this.style);

    }

 

    public void setStyle(String style) {

        this.style = style;

    }

 

 

    /**

     * CSS 类型 <code>class</code> 被应用于被选择节点的文本

     */

    protected String styleSelected = null;

 

    public String getStyleSelected() {

        return (this.styleSelected);

    }

 

    public void setStyleSelected(String styleSelected) {

        this.styleSelected = styleSelected;

    }

 

 

    /**

     * CSS 类型 <code>class</code>被应用于未选择

     * 节点的文本

     */

    protected String styleUnselected = null;

 

    public String getStyleUnselected() {

        return (this.styleUnselected);

    }

 

    public void setStyleUnselected(String styleUnselected) {

        this.styleUnselected = styleUnselected;

    }

 

 

    /**

     * The name of the attribute (in the specified scope) under which our

     * <code>clsTreeControl</code> instance is stored.

     */

    protected String tree = null;

 

    public String getTree() {

        return (this.tree);

    }

 

    public void setTree(String tree) {

        this.tree = tree;

    }

 

 

    // --------------------------------------------------------- 公用方法

 

 

    /**

     *控制树的绘制.

     *

     * @假若发生错误抛出 JspException 异常

     */

    public int redrawTree(JspWriter out) throws JspException {

 

        clsTreeControl treeControl =getTreeControl();

      // JspWriter out = pageContext.getOut();

        if(treeControl==null)

           if(this.control !=null)

              treeControl=this.control;

            else

             return -1;

        try {

            out.print

                ("<table  width='300%' border=/"0/" cellspacing=/"0/" cellpadding=/"0/"");

            if (style != null) {

                out.print(" class=/"");

                out.print(style);

                out.print("/"");

            }

            out.println(">");

            int level = 0;

            clsTreeNode node = treeControl.getRoot();

            render(out, node, level, treeControl.getWidth(), true);

            out.println("</table>");

        } catch (IOException e) {

            throw new JspException(e);

        }

 

        return (EVAL_PAGE);

 

    }

 

 

    /**

     *释放所有的状态信息

     */

    public void release() {

 

        this.action = null;

        this.images = DEFAULT_IMAGES;

        this.scope = null;

        this.style = null;

        this.styleSelected = null;

        this.styleUnselected = null;

        this.tree = null;

 

    }

 

 

    // ------------------------------------------------------ Protected Methods

 

 

    /**

     * 返回正在绘制的控制树的实例

     *

     *

     * @假如没有找到这棵控制树实例则抛出 JspException 异常

     */

    protected clsTreeControl getTreeControl() throws JspException {

 

        Object treeControl = null;

        if (scope == null)

            treeControl = pageContext.findAttribute(tree);

        else if ("page".equals(scope))

            treeControl =

                pageContext.getAttribute(tree, PageContext.PAGE_SCOPE);

        else if ("request".equals(scope))

            treeControl =

                pageContext.getAttribute(tree, PageContext.REQUEST_SCOPE);

        else if ("session".equals(scope))

            treeControl =

                pageContext.getAttribute(tree, PageContext.SESSION_SCOPE);

        else if ("application".equals(scope))

            treeControl =

                pageContext.getAttribute(tree, PageContext.APPLICATION_SCOPE);

        if (treeControl == null)

            throw new JspException("Cannot find tree control attribute '" +

                                   tree + "'");

        else if (!(treeControl instanceof clsTreeControl))

            throw new JspException("Invalid tree control attribute '" +

                                   tree + "'");

        else

            return ((clsTreeControl) treeControl);

 

    }

 

 

    /**

     * 绘制指定节点, .

     *

     * @param out 正在写的文档对像

     * @param node 当前节点

     * @param level 节点在树中的缩排级数

     * @param width 子树可显示的宽度

     * @param last   是否为父节点的最后一个节点?

     *

     * @如果发生一个输入/输出错误则抛出一个 IOException 异常

     */

    protected void render(JspWriter out, clsTreeNode node,

                          int level, int width, boolean last)

        throws IOException {

 

        HttpServletResponse response =

            (HttpServletResponse) pageContext.getResponse();

 

 

        //如果节点为根节点且标签内容为空,则不绘制这个棵树的根节点

        if ("ROOT-NODE".equalsIgnoreCase(node.getName()) &&

        (node.getLabel() == null)) {

            // 绘制孩子节点

            clsTreeNode children[] = node.findChildren();

            int lastIndex = children.length - 1;

            int newLevel = level + 1;

            for (int i = 0; i < children.length; i++) {

                render(out, children[i], newLevel, width, i == lastIndex);

            }

            return;

        }

 

        //开始绘制节点

        out.println("  <tr valign=/"middle/">");

 

        // 创建合适数量的缩排

        for (int i = 0; i < level; i++) {

            int levels = level - i;

            clsTreeNode parent = node;

            for (int j = 1; j <= levels; j++)

                parent = parent.getParent();

            if (parent.isLast())

                out.print("    <td width='5' >&nbsp;</td>");

            else {

                out.print(TD_WIDTH+"    <img src=/"");

                out.print(images);

                out.print("/");

                out.print(IMAGE_LINE_VERTICAL);

                out.print("/" alt=/"/" border=/"0/"></td>");

            }

            out.println();

        }

 

        // 绘制节点在树中的状态图标

 

        // HACK to take into account special characters like = and &

        // in the node name, could remove this code if encode URL

        // and later request.getParameter() could deal with = and &

        // character in parameter values.

        String encodedNodeName = URLEncoder.encode(node.getName());

 

        String action = replace(getAction(), "${name}", encodedNodeName);

 

 

        String updateTreeAction =

            replace(getAction(), "tree=${name}", "select=" + encodedNodeName);

        updateTreeAction =

            ((HttpServletResponse) pageContext.getResponse()).

            encodeURL(updateTreeAction);

 

        out.print(TD_WIDTH);

        if ((action != null) && !node.isLeaf()) {

            out.print("<a href=/"");

            out.print(response.encodeURL(action));

            out.print("?nodename="+node.getName());

            out.print("/">");

        }

         out.print("<img src=/"");

         out.print(images);

         out.print("/");

 

        if (node.isLeaf()) {

            if (node.isLast())

                out.print(IMAGE_LINE_LAST);

            else

                out.print(IMAGE_LINE_MIDDLE);

            out.print("/" alt=/"");

        } else if (node.isExpanded()) {

 

 

          if (node.isLast())

                out.print(IMAGE_HANDLE_DOWN_LAST);

            else

                out.print(IMAGE_HANDLE_DOWN_MIDDLE);

            out.print("/" alt=/"close node");

 

        } else {

 

          if (node.isLast())

                out.print(IMAGE_HANDLE_RIGHT_LAST);

            else

                out.print(IMAGE_HANDLE_RIGHT_MIDDLE);

            out.print("/" alt=/"expand node");

 

        }

 

         out.print("/" border=/"0/">");

        if ((action != null) && !node.isLeaf())

           out.print("</a>");

       out.println("</td>");

 

        //******************************************

 

        if ((action != null) && !node.isLeaf()) {

            out.print(TD_WIDTH);

            out.print("<a href=/"");

            out.print(response.encodeURL(action));

            out.print("?nodename="+node.getName());

            out.print("/">");

        }

 

 

 

        if(node.isExpanded()&&!node.isLeaf()) {

                out.print("<img src=/"");

                out.print(images);

                 out.print("/");

 

                if (node.isLast())

                  out.print(IMAGE_HANDLE_OPEN);

                else

                  out.print(IMAGE_HANDLE_OPEN);

                  out.print("/" alt=/"close node");

                  out.print("/" border=/"0/">");

                if ((action != null) && !node.isLeaf())

                  out.print("</a>");

                  out.println("</td>");

 

              } else if (!node.isLeaf()){

                out.print("<img src=/"");

                out.print(images);

                out.print("/");

 

                if (node.isLast()){

 

                    out.print(IMAGE_HANDLE_CLOSE);

 

                }

                else

                  out.print(IMAGE_HANDLE_CLOSE);

                out.print("/" alt=/"expand node");

                out.print("/" border=/"0/">");

                if ((action != null) && !node.isLeaf())

                  out.print("</a>");

                out.println("</td>");

 

              }

 

//*****************************************************

 

 

 

        // Calculate the hyperlink for this node (if any)

        String hyperlink = null;

        //Start Modify 2004/12/28 by Long

        String tmpAction=node.getAction();

        if(node.getAction()!=null){

            if (tmpAction.indexOf("?") >= 0)

                tmpAction += "&nodename=" + node.getName();

            else

                tmpAction += "?nodename=" + node.getName();

        }

        if (node.getAction() != null){

            //Start Modify 2004/12/28 by Long

            //hyperlink = ((HttpServletResponse) pageContext.getResponse()).

              //          encodeURL(node.getAction());

            hyperlink = ((HttpServletResponse) pageContext.getResponse()).

                        encodeURL(tmpAction);

            //end Modify 2004/12/28

        }

        // Render the icon for this node (if any)

      if (node.getIcon() != null&&node.isLeaf()) {

         out.print(TD_WIDTH);

        if (hyperlink != null) {

                 out.print("<a href=/"");

                 out.print(hyperlink);

                 out.print("/"");

                 String target = node.getTarget();

                 if(target != null) {

                     out.print(" target=/"");

                     out.print(target);

                     out.print("/"");

                 }

                 // to refresh the tree in the same 'self' frame

              //  out.print(" οnclick=/"");

 

             //   out.print("self.location.href='" + updateTreeAction+ "'");

 

             //  out.print("/"");

                 out.print(">");

             }

             if(node.isLeaf()){

               out.print("<img src=/"");

               out.print(images);

               out.print("/");

               out.print(node.getIcon());

               out.print("/" alt=/"");

               out.print("/" border=/"0/">");

               if (hyperlink != null)

                 out.print("</a>");

             }

             out.print("</td>");

 

         }

 

 

      out.print("    <td valign='center' align='left' colspan=/"");

        if(!node.isLeaf())

          out.print(width - level +2);

        else

          out.print(width - level +2);

        out.print("/">");

 

 

        // Render the label for this node (if any)

 

        if (node.getLabel() != null) {

            String labelStyle = null;

            if (node.isSelected() && (styleSelected != null))

                labelStyle = styleSelected;

            else if (!node.isSelected() && (styleUnselected != null))

                labelStyle = styleUnselected;

            if (hyperlink != null) {

                // Note the leading space so that the text has some space

                // between it and any preceding images

                out.print(" <a href=/"");

                out.print(hyperlink);

                out.print("/"");

                String target = node.getTarget();

                if(target != null) {

                    out.print(" target=/"");

                    out.print(target);

                    out.print("/"");

                }

                if (labelStyle != null) {

                    out.print(" class=/"");

                    out.print(labelStyle);

                    out.print("/"");

                }

                // to refresh the tree in the same 'self' frame

            //    out.print(" οnclick=/"");

          //     out.print("self.location.href='" + updateTreeAction  + "'");

           //    out.print("/"");

                out.print(">");

            } else if (labelStyle != null) {

                out.print("<span class=/"");

                out.print(labelStyle);

                out.print("/">");

            }

            out.print("<font color=/"");

            out.print(node.getLabelColor());

            out.print("/">");

            out.print(node.getLabel());

            out.print("</font>");

            if (hyperlink != null)

                out.print("</a>");

            else if (labelStyle != null)

                out.print("</span>");

        }

        out.println("</td>");

 

        // Render the end of this node

        out.println("  </tr>");

 

        // Render the children of this node

        if (node.isExpanded()) {

            clsTreeNode children[] = node.findChildren();

            int lastIndex = children.length - 1;

            int newLevel = level + 1;

            for (int i = 0; i < children.length; i++) {

                render(out, children[i], newLevel, width, i == lastIndex);

            }

        }

 

    }

 

 

    /**

     * Replace any occurrence of the specified placeholder in the specified

     * template string with the specified replacement value.

     *

     * @param template Pattern string possibly containing the placeholder

     * @param placeholder Placeholder expression to be replaced

     * @param value Replacement value for the placeholder

     */

    protected String replace(String template, String placeholder,

                             String value) {

 

        if (template == null)

            return (null);

        if ((placeholder == null) || (value == null))

            return (template);

        while (true) {

            int index = template.indexOf(placeholder);

            if (index < 0)

                break;

            StringBuffer temp = new StringBuffer(template.substring(0, index));

            temp.append(value);

            temp.append(template.substring(index + placeholder.length()));

            template = temp.toString();

        }

        return (template);

 

    }

 

    private void jbInit() throws Exception {

    }

 

 

}

4.必须有这如下几个图标文件,它们的分别是一线,文件之灰的图标

 

 

static final String IMAGE_HANDLE_DOWN_LAST =    "handledownlast.gif";

    static final String IMAGE_HANDLE_DOWN_MIDDLE =  "handledownmiddle.gif";

    static final String IMAGE_HANDLE_RIGHT_LAST =   "handlerightlast.gif";

    static final String IMAGE_HANDLE_RIGHT_MIDDLE = "handlerightmiddle.gif";

 

    static final String IMAGE_HANDLE_OPEN="ftv2folderopen.gif";

    static final String IMAGE_HANDLE_CLOSE="ftv2folderclosed.gif";

 

    static final String IMAGE_LINE_LAST =           "linelastnode.gif";

    static final String IMAGE_LINE_MIDDLE =         "linemiddlenode.gif";

    static final String IMAGE_LINE_VERTICAL =       "linevertical.gif";

 

默认存放在 /images 目录下面,用户可以自定义目录

 

5.使用实例 TreeView.jsp

 <%

   request.getParameter("nodename");

   clsTreeControl ctl=null;

            if(name==null)

            {

                   clsTreeNode root=new clsTreeNode(“ROOT_ID”,

                           "ftv2doc.gif",”根节点”,

                           null,"detail",true,"ds");

                  ctl=new clsTreeControl(root);

                  clsTreeNode firstNde=new clsTreeNode(“firstNde”,

                           "ftv2doc.gif",”搜狐网”,

                           “www.sohu.com”,"detail",true,"ds");

                  root.addChild(fisrtNde);

       clsTreeNode SecNde=new clsTreeNode(“SecNde”,

                           "ftv2doc.gif",”人民网”,

                           “www.peapole.com.cn”,"detail",true,"ds");

                       root.addChild(SecNde);

                session.setAttribute("tree1",ctl) ;

 

 

            }else{

               ctl=( clsTreeControl )session.getAttribute(“tree 1” );

                clsTreeNode node = ctl.findNode(name);

                node.setExpanded(!node.isExpanded());

                ctl.selectNode(name);

 

            }

            session.setAttribute("TREEVIEW",tree);

                        JspWriter write=pageContext.getOut();

            ctl=(clsTreeControl)session.getAttribute("tree1");

      clsDrawTree draw=new  clsDrawTree(ctl,pageContext);

      draw.setStyle("font1");

      draw.setTree("tree1") ;

      draw.setAction("drawTreeAction.do");

      String scope= new String("session");

      draw.setScope(scope);

      draw.redrawTree(write);

  %>

 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java在窗口中添加树形菜单TreeView源代码,分享给JAVA新手的一个例子,JTextField jtfInfo; //文本域,用于显示点击的节点称   public JTreeDemo(){    super("森林状的关系图"); //调用父类构造函数       DefaultMutableTreeNode root = new DefaultMutableTreeNode("设置"); //生成根节点    DefaultMutableTreeNode node1=new DefaultMutableTreeNode("常规"); //生成节点一    node1.add(new DefaultMutableTreeNode("默认路径")); //增加新节点到节点一上    node1.add(new DefaultMutableTreeNode("保存选项"));    root.add(node1); //增加节点一到根节点上    root.add(new DefaultMutableTreeNode("界面"));    root.add(new DefaultMutableTreeNode("提示声音"));    root.add(new DefaultMutableTreeNode("打印"));       JTree tree = new JTree(root); //得到JTree的实例    DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)tree.getCellRenderer(); //得到JTree的Renderer    renderer.setLeafIcon(null); //设置叶子节点图标为空    renderer.setClosedIcon(null); //设置关闭节点的图标为空    renderer.setOpenIcon(null); //设置打开节点的图标为空       tree.addTreeSelectionListener(new TreeSelectionListener() { //选择节点的事件处理    public void valueChanged(TreeSelectionEvent evt) {    TreePath path = evt.getPath(); //得到选择路径    String info=path.getLastPathComponent().toString(); //得到选择的节点称    jtfInfo.setText(info); //在文本域中显示称    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值