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

标签 java algorithm swing jpanel

我正在构建一个树遍历程序,它允许用户运行 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 获取字符串值...

谢谢!

最佳答案

假设 nodeList 是一个 ArrayList,尝试在调用 appendNode() 之前放置以下内容:

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

由于您已按照它们在 nodeList 中出现的相同顺序将节点添加到组合框中,从而使它们基本上成为镜像,所以上面的行应该有效。

关于java - 根据用户 TextField 和 JComboBox 输入将节点附加到 Parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17243518/

相关文章:

java - proguard 在发布版本中删除 chunktemplate 功能

java - java 中带有抽象类的 jar 的误导行为

python - 重复删除出现的子字符串,直到主字符串为空

algorithm - 将多边形顶点数组 "match"到另一个数组的最佳方法?

c++ - 如何实现排队 map ?

java - JMS - 查找问题

java - Java 泛型中的 Get-Put 原则

java - 如何管理调用另一个 JInternalFrame 的 JInternalFrame?

java - 禁用 DataGrid 的特定列

java - 降雨量图 - 文本字段填充数组