【问题标题】:Building JTree from strings从字符串构建 JTree
【发布时间】:2012-12-05 14:21:11
【问题描述】:

我有两个字符串 node1/node2/node3/node4" 和 "node1/node2/node5/node6".... 我怎样才能从这个字符串中构建一个 JTree 摆动?这是我构建的代码一串……

import java.awt.*;  
import java.util.ArrayList;

import javax.swing.*;  
import javax.swing.tree.*;  

public class PathTest  
{  
    public PathTest()  
    {  

    DefaultMutableTreeNode   node = buildNodeFromString();   


        DefaultTreeModel model = new DefaultTreeModel(node);  
        JTree tree = new JTree(model);  
        JFrame f = new JFrame();  
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        f.add(tree);  
        f.setSize(300,300);  
        f.setLocation(200,200);  
        f.setVisible(true);  
    }  

private DefaultMutableTreeNode buildNodeFromString() {



String qqq= "node1/node2/node3/node4";
DefaultMutableTreeNode node, lastNode = null, root = null;

    String[] s = qqq.split("/");
    for (String str : s) {
    node = new DefaultMutableTreeNode(str);     
    if (root == null)
        root = node;
    if (lastNode != null)
        lastNode.add(node);
    lastNode = node;
    }

return root;
}

    public static void main(String[] args)  
    {  
        new PathTest();  
    }  
}  

【问题讨论】:

    标签: java string swing jtree treenode


    【解决方案1】:

    试试这个,这段代码为树创建了一个根,然后开始在它下面添加字符串,如果你不想显示那个根,只需调用tree.setRootVisible(false);

    import java.util.Enumeration;
    
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    
    public class PathTest {
        public PathTest() {
            // Create the root node, I'm assuming that the delimited strings will have
            // different string value at index 0
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("ROOT");
    
            // Create the tree model and add the root node to it
            DefaultTreeModel model = new DefaultTreeModel(root);
    
            // Create the tree with the new model
            JTree tree = new JTree(model);
    
            // Build the tree from the various string samples
            buildTreeFromString(model, "Node 1/Node 2/Node 3/Node 4");
            buildTreeFromString(model, "Node 1/Node 2/Node 3/Node 5");
            buildTreeFromString(model, "Node 1/Node 2/Node 3/Node 6");
            buildTreeFromString(model, "Node 1/Node 2/Node 4/Node 5");
            buildTreeFromString(model, "Node 1/Node 1/Node 3/Node 5");
    
            // UI
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(tree);
            f.setSize(300, 300);
            f.setLocation(200, 200);
            f.setVisible(true);
        }
    
        /**
         * Builds a tree from a given forward slash delimited string.
         * 
         * @param model The tree model
         * @param str The string to build the tree from
         */
        private void buildTreeFromString(final DefaultTreeModel model, final String str) {
            // Fetch the root node
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
    
            // Split the string around the delimiter
            String [] strings = str.split("/");
    
            // Create a node object to use for traversing down the tree as it 
            // is being created
            DefaultMutableTreeNode node = root;
    
            // Iterate of the string array
            for (String s: strings) {
                // Look for the index of a node at the current level that
                // has a value equal to the current string
                int index = childIndex(node, s);
    
                // Index less than 0, this is a new node not currently present on the tree
                if (index < 0) {
                    // Add the new node
                    DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(s);
                    node.insert(newChild, node.getChildCount());
                    node = newChild;
                }
                // Else, existing node, skip to the next string
                else {
                    node = (DefaultMutableTreeNode) node.getChildAt(index);
                }
            }
        }
    
        /**
         * Returns the index of a child of a given node, provided its string value.
         * 
         * @param node The node to search its children
         * @param childValue The value of the child to compare with
         * @return The index
         */
        private int childIndex(final DefaultMutableTreeNode node, final String childValue) {
            Enumeration<DefaultMutableTreeNode> children = node.children();
            DefaultMutableTreeNode child = null;
            int index = -1;
    
            while (children.hasMoreElements() && index < 0) {
                child = children.nextElement();
    
                if (child.getUserObject() != null && childValue.equals(child.getUserObject())) {
                    index = node.getIndex(child);
                }
            }
    
            return index;
        }
    
        public static void main(String[] args) {
            new PathTest();
        }
    }
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:
      for (String str : s) {
          node = new DefaultMutableTreeNode(str);     
          if (root == null)
               root = node;
          if (lastNode != null)
              lastNode.add(node);
          lastNode = node;
      }
      

      在代码 sn-p 中,不是创建新的 DefaultMutableTreeNode 实例,而是检查 lastNode 是否已经有一个同名的子节点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-29
        • 2014-03-15
        • 1970-01-01
        • 2017-11-30
        • 1970-01-01
        • 2015-02-06
        • 1970-01-01
        相关资源
        最近更新 更多