根据用户TextField和JComboBox输入将节点附加到Parent

时间:2013-06-21 20:09:44

标签: java algorithm swing jpanel

我正在构建一个Tree遍历程序,它允许用户运行BFS和DFS遍历,以及添加和删除节点。

我坚持的是从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 个答案:

答案 0 :(得分:1)

假设nodeListArrayList,请在调用appendNode()之前尝试执行以下操作:

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

由于您已按照它们在nodeList中显示的顺序将节点添加到组合框中,使它们基本上被镜像,因此上述行应该有效。