Assign DefaultMutableTreeNode to JTree

£可爱£侵袭症+ 提交于 2020-01-13 21:10:41

问题


I am developing a small desktop application in Netbeans. I drag and drop a JTree on my JFrame and now i want to fill the node hierarchy of this this JTree dynamically. For this i worte a method which return me DefaultMutableTreeNode object. Now how do i assign this object to the JTree which i drag and drop


回答1:


following example will help you to do it

package commondemo;
/**
*
* @author hemant
 */
 import java.awt.*;
 import javax.swing.*;
 import javax.swing.tree.*;

 public class SimpleTree extends JFrame {
 public static void main(String[] args) {
 new SimpleTree();
}

public SimpleTree() {
super("Creating a Simple JTree");


Container content = getContentPane();
Object[] hierarchy =
  { "javax.swing",
    "javax.swing.border",
    "javax.swing.colorchooser",
    "javax.swing.event",
    "javax.swing.filechooser",
    new Object[] { "javax.swing.plaf",
                   "javax.swing.plaf.basic",
                   "javax.swing.plaf.metal",
                   "javax.swing.plaf.multi" },
    "javax.swing.table",
    new Object[] { "javax.swing.text",
                   new Object[] { "javax.swing.text.html",
                                  "javax.swing.text.html.parser" },
                   "javax.swing.text.rtf" },
    "javax.swing.tree",
    "javax.swing.undo" };
DefaultMutableTreeNode root = processHierarchy(hierarchy);
JTree tree = new JTree(root);
content.add(new JScrollPane(tree), BorderLayout.CENTER);
setSize(275, 300);
setVisible(true);
}

/** Small routine that will make node out of the first entry
*  in the array, then make nodes out of subsequent entries
*  and make them child nodes of the first one. The process is
*  repeated recursively for entries that are arrays.
*/

private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
 DefaultMutableTreeNode node =
   new DefaultMutableTreeNode(hierarchy[0]);
 DefaultMutableTreeNode child;
for(int i=1; i<hierarchy.length; i++) {
  Object nodeSpecifier = hierarchy[i];
  if (nodeSpecifier instanceof Object[])  // Ie node with children
    child = processHierarchy((Object[])nodeSpecifier);
  else
    child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
  node.add(child);
}
return(node);
}
}



回答2:


How to Use Trees



来源:https://stackoverflow.com/questions/7835962/assign-defaultmutabletreenode-to-jtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!