JTree: how to get the text of all items?

strizhechenko picture strizhechenko · Feb 7, 2011 · Viewed 9.9k times · Source

I want to get text of an JTree in format:

root
  sudir1
    node1
    node2
  subdir2
    node3
    node4

Is it possible?

I wrote some code

public static String getLastSelectedText(JTree tree) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    if (node == null) return null;
    return node.getUserObject().toString();
}

But it get only selected component text.

I think about expand tree and handle all nodes, but maybe it bad idea.

Answer

Howard picture Howard · Feb 7, 2011

I think you shouldn't build the string within a single function - but I do not know what exactly you aim at with your question.

In order to keep my answer as close to your suggested function as possible you may try something like this:

TreeModel model = tree.getModel();
System.out.println(getTreeText(model, model.getRoot(), ""));

with recursive function getTreeText

private static String getTreeText(TreeModel model, Object object, String indent) {
    String myRow = indent + object + "\n";
    for (int i = 0; i < model.getChildCount(object); i++) {
        myRow += getTreeText(model, model.getChild(object, i), indent + "  ");
    }
    return myRow;
}

getTreeText takes three arguments

  • model: The model which we request for tree nodes
  • object: The object we ask a string representation for (including all children)
  • indent: indentation level