Take the 2-minute tour ×

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:


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.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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...
        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 = 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.

share|improve this answer
Thank you very much, this is exactly what I needed. –  ShamanMaster Oct 31 '12 at 10:52
No problem. Please remember to 'tick' this answer if you think its the best, so that everyone else knows your problem was solved. –  WATTO Studios Oct 31 '12 at 10:52
Here is an additional method to get the name of object from the treePath: public static String getElementName(TreePath path) { Object[] nodes = path.getPath(); String result = ""; //read the path, start from index 1 because we don't want the root for (int i=1; i<nodes.length; i++) { result += nodes[i]; //add separator if (i!=nodes.length-1) result += "."; } return result; } –  ShamanMaster Oct 31 '12 at 11:04
share|improve this answer

Your Answer


