在Java swing中查找树节点的下一次出现 [英] find next occurence of tree node in java swing
问题描述
我有一个jtree.我已经写了代码,当单击搜索按钮时,可以在树中搜索给定的节点,现在我必须搜索下一次出现(如果存在),并再次单击该按钮?你能帮我吗? 搜索按钮的代码是
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");
}
}
});
搜索方法的代码是
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;
}
推荐答案
返回仅找到一个节点的列表,而不是仅返回一个节点.
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;
}
亲自执行按钮ActionListener
的逻辑,这并不难.
Do the logic for button ActionListener
yourself, it isn't that hard.
添加节点列表作为您的类成员,当您单击按钮时检查它是否为空,如果为空,则获取列表,获取第一个节点;用它做任何您想做的事,并将其从列表中删除.当您到达最后一个元素时,将列表再次设置为null.
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.
这篇关于在Java swing中查找树节点的下一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!