find next occurence of tree node in java swing

你。 提交于 2019-12-20 04:20:41

问题


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;

}


回答1:


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.



来源:https://stackoverflow.com/questions/12458403/find-next-occurence-of-tree-node-in-java-swing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!