Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTree: how to get the text of all items?

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.

like image 213
strizhechenko Avatar asked Feb 07 '11 05:02

strizhechenko


2 Answers

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
like image 105
Howard Avatar answered Oct 11 '22 21:10

Howard


    DefaultMutableTreeNode root = (DefaultMutableTreeNode)jTree.getModel().getRoot();
    Enumeration e = root.preorderEnumeration();
    while(e.hasMoreElements()){
        System.out.println(e.nextElement());
    }
like image 45
Vinil Chandran Avatar answered Oct 11 '22 23:10

Vinil Chandran