2013-06-21 44 views
0

我正在構建樹遍歷程序,該程序允許用戶運行BFS和DFS遍歷以及添加和刪除節點。基於用戶TextField和JComboBox輸入向父節點追加節點

我堅持的是從JComboBox獲取節點並將它傳遞給appendNode()。我想實現這一點:

enter image description here

首先,我添加和連接一串節點... addNode()添加節點的nodeList

然後我的所有節點添加到JComboBox中parents

for (Nodes n : nodeList) { 
    parents.addItem(n.getValue()); 
} 

正如你可以在上面看到,節點被成功添加到JComboBox中。

然後,我創建一個新的類:

//send in selected parent from combo box 
    AppendChildren ac = new AppendChildren(child, parents); 
    this.child.addActionListener(ac); 
    this.AddButton.addActionListener(ac); 

這使得使用這個類...

class AppendChildren implements ActionListener { 

    private TextField child; 
    private JComboBox parents; 
    private int index; 


    public AppendChildren(TextField child, JComboBox parent, int parentIndex) { 
    this.child = child; 
    this.parents = parent; 
    this.index = parentIndex; 
    } 

    public void actionPerformed(ActionEvent ae) { 
     //set max input to 2 characters 
     if (child.getText().length() <= 0) { 
      addMoreMessage = "Please name your child..."; 
     } 
     else { 
      addMoreMessage = ""; 
     } 
     if (child.getText().length()>1) { 
      child.setText(child.getText().substring(0,1)); 
     } 
     String childName = child.getText(); 
     parents.setSelectedIndex(index); 
     Nodes newChild = new Nodes(childName, nodeX, nodeY, nodeWidth, nodeHeight); 

     appendNode(parentNode, newChild); 
    } 
} 

其中要求appendNode(Nodes parent, Nodes child) {連接的節點並重新創建鄰接矩陣。

我的問題是:如何從JComboBox中選擇節點並將其傳遞到appendNode()?我能夠從TextField獲得字符串值就好...

謝謝!

回答

1

假設nodeListArrayList,可以嘗試以下的appendNode()呼叫前:

Nodes parentNode = nodeList.get(parents.getSelectedIndex()); 

既然你已經添加的節點到組合框以相同的順序,它們出現在nodeList使他們基本上是鏡像,上面的行應該工作。