1
我是Jtree和Java的新手。 我有一個樹形結構是這樣的:我如何得到Jtree Java中所有父節點的葉節點數
-Abcd
--Efghi
---Pqrst
---Uvwxyz
---Xyza
---Hdwik
---Lmnop
---Bcdef
--Tqrsp
---Jumak
----Uoaha
----Lobte
-----Cshnt
----Karke
現在我想ABCD的數量= 14(即ABCD的所有兒童的計數+ 1) 同樣,ABCD - Efghi = 7(即計數Efghi的所有葉節點+ 1)
但我無法獲得計數。 下面的代碼:
import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.io.*;
import java.util.*;
public class treeTest {
public treeTest(List<String> somelist) {
DefaultMutableTreeNode root = new DefaultMutableTreeNode(somelist.get(0));
DefaultTreeModel model = new DefaultTreeModel(root);
JTree tree = new JTree(model);
for(int i = 1;i<somelist.size();i++)
{
buildTreeFromString(model, somelist.get(i));
}
// 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);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
DefaultMutableTreeNode rootNode = ((DefaultMutableTreeNode)tree.getModel().getRoot());
int n = tree.getModel().getChildCount(rootNode);
System.out.println(n);
}
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);
}
}
}
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) throws FileNotFoundException, IOException {
List<String> list = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("Filepath\Sample.txt"));
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
reader.close();
new treeTest(list);
}
}
有什麼辦法,我可以讓每一個家長的leafcount樹或有任何其他的方式來獲得,而無需使用樹的信息?
謝謝你,我遍歷樹並得到了計數 –