I would like my JTree to be dynamically updated by a user initiated search (over elements of the tree). From output on the console I can tell, that the search works like it should. The problem is updating the tree.
Here is what I got. I have a set of classes like
public class classA {
int id;
String name;
List<ClassB> listOfClassB;
}
public class classB {
int id;
String name;
List<ClassC> listOfClassC;
}
public class classC {
int id;
String name;
}
From these classes I generate a JTree by looping throught the classes lists in createTree().
private DefaultMutableTreeNode rootNode;
rootNode = createTree("New", ""); // "New" tells the method to generate the complete tree
treeModel = new DefaultTreeModel(rootNode);
JTree myTree = new JTree(treeModel);
So far so good. Now I want to search the tree for a String or Int in classC.name or classC.id and "remove" all nodes that do not match the search criteria. But not the objects, only the corresponding tree nodes. So that when the user is done searching I can show the whole tree again.
The search is implemented with JTextField and a KeyListener that calls createTree(searchOption, searchText).
So far I have tried to remove all nodes with removeAllChildren()and then add new nodes that match the search criteria. Reloading the TreeModel afterwards does not seem to work here.
createTree(searchOption, searchText);
rootNode.removeAllChildren();
treeModel.reload(rootNode);
Any ideas how I could accomplish that?
PS: I chose to delete the tree and generate a new one to avoid keeping the tree and the data in sync because it seems way more complicated.
I did manage to load a "new" tree by creating and setting a new root node before reloading the model. It does not seem "clean" to me, but it did the trick.
rootNode = createTree(searchOption, searchText);
treeModel.setRoot(rootNode);
treeModel.reload();