gpt4 book ai didi

java - JTree For 循环数组语法

转载 作者:行者123 更新时间:2023-12-01 14:19:18 24 4
gpt4 key购买 nike

对 for 循环的语法有困难,该循环从数组读取数据并将其添加到 JTree .

public void init()
{ final String section1 = "JAVA";
String[] sections = new String[]{ "Tutorial6", "Tutorial5", "Tutorial4", "Tutorial3", "Tutorial2", "Tutorial1" };

String contents[][] = {
{"content1a", "content1b"},
{"content2a", "content2b"},
{"content3a", "content3b"}
};

title = new DefaultMutableTreeNode(section1);

for (int i=0; i<sections.length; i++)
{ selection = new DefaultMutableTreeNode(( sections[i]));

selection.insert(new DefaultMutableTreeNode((contents[i])),0);



//title.insert(selection,0);
}

添加部分工作正常,但向这些部分添加节点是问题。如何让 for 循环工作,以便在解析 for 循环时将具有内容名称的节点添加到相关部分? ??

这是不起作用的代码:

    selection.insert(new DefaultMutableTreeNode((contents[i])),0);

谢谢!!

最佳答案

创建一个 TreeNode 实际上是一个单一的节点。因此,将数组传递给节点构造函数不会创建完整的节点列表。为了实现你想要的,添加一个嵌套的for循环。

String contents[][] =
{
{"content1a", "content1b"},
{"content2a", "content2b"},
{"content3a", "content3b"}
};

title = new DefaultMutableTreeNode(section1);

for (int i=0; i < sections.length; i++)
{
selection = new DefaultMutableTreeNode(sections[i]);
for (int k = 0; k < contents[i].length; ++k)
{
selection.add(new DefaultMutableTreeNode(contents[i][k]));
}
title.add(selection);
}

关于java - JTree For 循环数组语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17765539/

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