Search code examples
javaswingjtreetreenodetreemodel

Create a JTree from a list of dot-delimited Strings


I am creating an editor application, and I am having a problem with my menus. In the object menu, I want to display several objects types using a JTree. These object types are dynamically registered by plugins and follow this style:

trigger.button
trigger.lever
out.door.fallgate
trigger.plate
out.door.door
...

This list of names is unsorted and I want to build a TreeNode structure for a JTree like this:

  • trigger
    • button
    • lever
    • plate
  • out
    • door
      • fallgate
      • door

Additionally, if the user selects a leaf node, I need to recreate the object name (e.g. trigger.button) from the TreePath. Could someone please advise how this can be done.


Solution

  • In psuedocode, this is what you need to do...

    public TreeNode buildTree(){
        String[] names = new String[]; // fill this with the names of your plugins
    
        TreeNode tree;
    
        // for each plugin name...
        for (int i=0;i<names.length;i++){
            String currentName = names[i];
            String[] splitName = currentName.split(".");
    
            // loop over the split name and see if the nodes exist in the tree. If not, create them
            TreeNode parent = tree;
            for (int n=0;n<splitName.length;n++){
                if (parent.hasChild(splitName[n])){
                    // the parent node exists, so it doesn't need to be created. Store the node as 'parent' to use in the next loop run
                    parent = parent.getChild(splitName[n]);
                }
                else {
                    // the node doesn't exist, so create it. Then set it as 'parent' for use by the next loop run
                    TreeNode child = new TreeNode(splitName[n]);
                    parent.addChild(child);
                    parent = child;
                }
            }
    
    return tree;
    }
    

    This is only psuedocode - you'll need to do the work of implementing the TreeNode methods properly, etc. Give it a try yourself - if you have any more problems, create a question and show us that you've attempted to do it yourself, then we will be more willing to help you solve the minor problems.