2012-09-17 21 views
1

我有一個jtree。我已經寫了代碼來搜索樹中的給定節點,當搜索按鈕被點擊時,現在我必須搜索下一個發生,如果存在與另一個點擊該按鈕?你能幫我嗎? 搜索按鈕的代碼是在java swing中發現下一個樹節點的發生

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; 

}

回答

2

而不是隻返回一個節點,返回找到節點列表。

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的邏輯,並不難。

添加節點列表作爲您的類成員,當您單擊按鈕時檢查它是否爲空,如果是,請檢索列表,獲取第一個節點;做任何你想要的東西,並從列表中刪除它。當你到達最後一個元素時,將列表再次設置爲空。

+0

沒有理由向util.List添加節點,因爲所有元素都存儲在DefaultTreeModel, – mKorbel

+0

@mKorbel:可能'List'或'Map'到[cache](http://stackoverflow.com/q/224868/230513)找到節點供以後導航? – trashgod