简体   繁体   English

如何从自定义树创建JPopupMenu

[英]How to create JPopupMenu From Custom Tree

The method below creates Custom Data Tree from A String. 下面的方法根据字符串创建自定义数据树。

I am working on a method that generates pop-up menu with many submenus. 我正在研究一种生成带有许多子菜单的弹出菜单的方法。 Basically these menus given dynamically so I have an algorithm to handle creating submenus using below string. 基本上,这些菜单是动态提供的,因此我有一种算法可以处理下面的字符串创建子菜单。 In order to do it I transform this string into Java Custom Tree by splitting using the delimiter. 为了做到这一点,我通过使用定界符进行分割将该字符串转换为Java Custom Tree。

public class MenuItem {

    public String Name;
    public Vector<MenuItem> Childeren;


    public MenuItem() {
        Name = "";
        Childeren = new Vector<MenuItem>();
    }

    public MenuItem(String name) {
        this();
        Name = name;
    }


    public String toString() {
        return Name + " " + Childeren ;
    }
}


public static int createNode(StringTokenizer p_jTokenizer, MenuItem p_iParent) {
    int nCount = 0;

    while(p_jTokenizer.hasMoreTokens()) {
        String strToken = p_jTokenizer.nextToken();

        MenuItem iItem = new MenuItem();

        if(strToken.endsWith("[")) {           
            strToken = strToken.substring(0, strToken.length() - 1);
            nCount =  createNode(p_jTokenizer, iItem);
        }           

        while(strToken.endsWith("]")) {
            nCount++;
            strToken = strToken.substring(0, strToken.length() - 1);               
        }

        iItem.Name = strToken;           
        p_iParent.Childeren.add(iItem);

        while(nCount > 0) {
            return --nCount;
        }
    }
    return nCount;
}

An Example of Dynamic String Values that I parse: 我解析的动态字符串值的示例:

String str = "Menu1;Menu2[;Menu2A;Menu2B[;Menu2B-A;Menu2B-B]];Menu3;"; 字符串str =“ Menu1; Menu2 [; Menu2A; Menu2B [; Menu2B-A; Menu2B-B]]; Menu3;”;

The current method creates a tree like below structure: 当前方法将创建如下结构的树:

                             Pop-up Menu
                             /    |     \
                       Menu1    Menu2   Menu3
                             /     | 

                          Menu2A     Menu2B
                                      |       \
                                      |        \
                                   Menu2B-A  Menu2B-B

I am stuck on how to create JPopUpMenu with submenus based on this tree. 我被困在如何使用基于此树的子菜单创建JPopUpMenu的问题上。 I think of using recursive way but not sure which way to go. 我想使用递归方法,但不确定该走哪条路。

Iterate through the tree structure. 遍历树结构。 If an element is node create JMenu if it's leaf create JMenuItem add all the children to the JMenu. 如果元素是节点,则创建JMenu;如果元素是叶,则创建JMenu;将所有子代添加到JMenu。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM