Nikhil
Nikhil

Reputation: 2883

find next occurence of tree node in java swing

I have a jtree. i have written the code to search a given node in the tree when search button clicked is worked and now i have to search the next occurence if exist with another click on that button? can you help? code for search button is

 m_searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
    DefaultMutableTreeNode node = searchNode(m_searchText.getText());
    if (node != null) {
      TreeNode[] nodes = m_model.getPathToRoot(node);
      TreePath path = new TreePath(nodes);
      m_tree.scrollPathToVisible(path);
      m_tree.setSelectionPath(path);
    } else {
      System.out.println("Node with string " + m_searchText.getText() + " not found");
    }
}

});

code for the search method is

public DefaultMutableTreeNode searchNode(String nodeStr) {
DefaultMutableTreeNode node = null;
Enumeration e = m_rootNode.breadthFirstEnumeration();
while (e.hasMoreElements()) {
  node = (DefaultMutableTreeNode) e.nextElement();
  if (nodeStr.equals(node.getUserObject().toString())) {
    return node;
  }
}
return null;

}

Upvotes: 1

Views: 866

Answers (1)

nullpotent
nullpotent

Reputation: 9260

Instead of returning just one node, return a list of found nodes.

public List<DefaultMutableTreeNode> searchNode(String nodeStr) {
DefaultMutableTreeNode node = null;
Enumeration e = m_rootNode.breadthFirstEnumeration();
List<DefaultMutableTreeNode> list = new ArrayList<DefaultMutableTreeNode>();
while (e.hasMoreElements()) {
  node = (DefaultMutableTreeNode) e.nextElement();
  if (nodeStr.equals(node.getUserObject().toString())) {
    list.add(node);
  }
}
return list;
}

Do the logic for button ActionListener yourself, it isn't that hard.

Add the list of nodes as your class member, when you click on the button check if it's null, if it is, retrieve the list, get the first node; do whatever you want with it and remove it from the list. When you get to the last element set the list to be null again.

Upvotes: 2

Related Questions