mbasol
mbasol

Reputation: 105

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.

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;";

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. I think of using recursive way but not sure which way to go.

Upvotes: 1

Views: 292

Answers (1)

StanislavL
StanislavL

Reputation: 57381

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.

Upvotes: 1

Related Questions