Если мы предположим, что у вас есть TreeModel
(которые вы можете получить от JTree
с помощью JTree.getModel()
), то следующий код будет распечатать листья дерева в «/» - отделенного формат, который вы ищете:
/**
* Prints the path to each leaf in the given tree to the console as a
* "/"-separated string.
*
* @param tree
* the tree to print
*/
private void printTreeLeaves(TreeModel tree) {
printTreeLeavesRecursive(tree, tree.getRoot(), new LinkedList<Object>());
}
/**
* Prints the path to each leaf in the given subtree of the given tree to
* the console as a "/"-separated string.
*
* @param tree
* the tree that is being printed
* @param node
* the root of the subtree to print
* @param path
* the path to the given node
*/
private void printTreeLeavesRecursive(TreeModel tree,
Object node,
List<Object> path) {
if (tree.getChildCount(node) == 0) {
for (final Object pathEntry : path) {
System.out.print("/");
System.out.print(pathEntry);
}
System.out.print("/");
System.out.println(node);
}
else {
for (int i = 0; i < tree.getChildCount(node); i++) {
final List<Object> nodePath = new LinkedList<Object>(path);
nodePath.add(node);
printTreeLeavesRecursive(tree,
tree.getChild(node, i),
nodePath);
}
}
}
конечно, если вы не просто хотите, чтобы распечатать содержимое дерева на консоли, вы можете заменить println
заявления с чем-то другим, например, вывод в файл или, например, как запись или добавление к Writer
или StringBuilder
, который передается этим методам в качестве дополнительного аргумента.
Вы говорите, что у вас есть JTree? – Wintermut3
Я придумал две возможные интерпретации вопроса и попытался ответить на оба из них. Надеюсь, по крайней мере один ответ будет полезен. :-) –
Я предполагаю, что приложение имеет JTree, но у меня нет прямого доступа к нему. Для этого могут потребоваться сообщения Windows или что-то уродливое. – User1