gpt4 book ai didi

java - 从数组列表创建 Swing 树

转载 作者:行者123 更新时间:2023-12-01 10:03:03 28 4
gpt4 key购买 nike

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

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 显示为根节点,下面没有其他内容。有什么想法我做错了什么吗?

最佳答案

这对我有用:

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;
}
}

关于java - 从数组列表创建 Swing 树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36665352/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com