简体   繁体   中英

Dynamic JTree updated by KeyListener in a JTextField

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.

JTree myTree = new JTree(treeModel);

That statement doesn't look correct. You create a new JTree but I don't see where you add the tree back to the frame.

Instead of creating a new tree, just resetting the model of the tree:

myTree.setModel( treeModel );

The search is implemented with JTextField and a KeyListener that calls createTree(searchOption, searchText).

Don't use a KeyListener. You should be using a DocumentListener to listen for changes in text. Read the section from the Swing tutorial on Listener For Change on a Document .

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM