从数组列表创建Swing Tree

时间:2016-04-16 14:23:55

标签: java swing arraylist jtree primavera

我有一个包含两列的数组列表,一列有子列,另一列有父列,例如

label                     Parent

Test
something 1               Test
Something 2               Test
Something 3               Something 1
Something 4               Something 1
Something 5               Something 1
Something 6               Something 5

以下是我用来创建树的代码:

DefaultMutableTreeNode root = new DefaultMutableTreeNode(nodeList.get(0).label);
findChild(root, nodeList);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = frame.getContentPane();
final JTree tree = new JTree(root);

static void findChild(DefaultMutableTreeNode parent, List<Node> nodeList2) {

    for (int i = 0; i < nodeList2.size(); i++) {
        if (nodeList2.get(i).parent != null && nodeList2.get(i).parent.equals(parent.toString())) {
            DefaultMutableTreeNode child = new DefaultMutableTreeNode(nodeList2.get(i).label);
            Parent.add(child);
            findChild(child, nodeList2); // child of child
        }
    }
}

问题是我只是将Test显示为根节点,在其下面没有其他任何内容。 有什么想法我做错了吗?

1 个答案:

答案 0 :(得分:1)

这对我有用:

import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.tree.*;

public class TreeTest {
  public JComponent makeUI() {
    List<Node> nodeList = new ArrayList<>();
    nodeList.add(new Node("Test"));
    //typo? nodeList.add(new Node("something 1", "Test"));
    nodeList.add(new Node("Something 1", "Test"));
    nodeList.add(new Node("Something 2", "Test"));
    nodeList.add(new Node("Something 3", "Something 1"));
    nodeList.add(new Node("Something 4", "Something 1"));
    nodeList.add(new Node("Something 5", "Something 1"));
    nodeList.add(new Node("Something 6", "Something 5"));

    DefaultMutableTreeNode root = new DefaultMutableTreeNode(nodeList.get(0).label);
    findChild(root, nodeList);
    JTree tree = new JTree(root);
    return new JScrollPane(tree);
  }
  private static void findChild(DefaultMutableTreeNode parent, List<Node> list) {
    for (int i = 0; i < list.size(); i++) {
      if (list.get(i).parent != null && list.get(i).parent.equals(parent.toString())) {
        DefaultMutableTreeNode child = new DefaultMutableTreeNode(list.get(i).label);
        parent.add(child);
        findChild(child, list); // child of child
      }
    }
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new TreeTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}

class Node {
  public final String label;
  public final String parent;
  public Node(String label) {
    this(label, null);
  }
  public Node(String label, String parent) {
    this.label = label;
    this.parent = parent;
  }
}